What are loops and Iteration in Dart ?

At times, certain instructions require repeated execution. Loops are an ideal way to do the same. A loop represents a set of instructions that must be repeated. In a loop’s context, a repetition is termed as an iteration.

The following figure illustrates the classification of loops −

loop is used in Dart or any other programming language to repeat a sequence of commands a given number of times or until it satisfies a condition.

It is convenient for iterating over a collection/list of items or repeating an operation.

The following are loops used in Dart programming:

  1. for loop
  2. for...in loop
  3. for each loop
  4. while loop
  5. do-while loop

All the loop types mentioned above have the following characteristics:

  • Counter Variable – Also known as the Initializer. It keeps track of the number of times a loop is executed.
  • Increment or Decrement Counter Variable – This refers to the number in which counter variable increases or decreases after each iteration.
  • Condition Check – Every loop will have a condition that will be checked on each Iteration. If the condition is evaluated to true, then the next iteration will get executed.

Loops can be classified into two types based on condition checking:

  1. Entry controlled loops – These are loops in which the condition is checked first and then the iteration is executed.
  2. Exit controlled loops – These are loops in which an iteration is executed and then the condition is checked afterwards.

For loop

Syntax of For loop:

void main(){

   for (initialize counter variable; condition; increment/decrement){  
       //put your code here;
   }

}

How the For loop works:

Initialize counter – Condition check – Execute code – Increment.

  1. The counter variable is initialized. The initialization occurs only once, it won’t be executed on every iteration.
  2. Then the condition is checked. If the condition is evaluated as true, then the code block will be executed. If not, the code block will not be executed.
  3. The counter variable will be incremented and the condition is evaluated again with the new value of the counter variable. This process repeats itself until the condition isn’t met.

Example:

void main(){
  for(var i = 0; i<4; i++){
     print ("Hello flutterfever");
   }
}

Output :

Hello flutterfever
Hello flutterfever
Hello flutterfever
Hello flutterfever

Here the value of the counter variable will increase by 1 for every iteration. If the value of i becomes equal to 4 or more, the loop will be terminated since the condition states that the value of i should be less than 4. The code block prints Hello, hence the output is Hello written four times for (0,1,2,3) < 4.

for...in loop

The for in loop uses an expression or object as an iterator to loop through the elements one by one in order.

Syntax:
for (var in expr) {
   //Body of the loop
}
// Using for...in loop to print out elements in the list

void main()
{
  var shots = ['for', 'in', 'loop', 'in', 'Dart', 'Programming'];
  for (var i in shots){
    print(i);
  }
}

Output
for
in
loop
in
Dart
Programming

for each loop

The for each loop iterates over all the elements in some collectible and passes the elements to some specific function.

Syntax:
iterable.foreach(void func(value))
// Using forEachloop to print out elements in the list
void main()
{
  var num = [1, 2, 3, 4, 5, 6];
  num.forEach((var item){
    if(item %2 == 0){ //checks for even numbers in num list
      var myList = [item];
      print(myList); //print even numbers
    }
  });
}
Output

[2]
[4]
[6]

While loop

Syntax of a While loop:

void Main(){
   
   // initialize counter variable;
   while(condition){
      //code;
      //increment/decrement;
    }

}

How the While loop works:

Initialize counter – Condition check – Execute code – Increment.

  1. We Initialize the counter variable outside the while block.
  2. It begins with the condition check, if it’s true, then the code block will be executed.
  3. The value of the counter variable is incremented or decremented, and the new value of the counter variable goes through the condition check.
  4. This process will continue until the condition check is false.

NOTE: We must always increment/decrement the counter variable inside the while block. Failure to do so will create a never-ending loop.

Example:

void main(){
  int i = 0;
   while(i<3){
      print("flutterfever");
      i++;
   }
}

Output:

flutterfever
flutterfever
flutterfever

Our condition check will begin with the statement 0 < 3 which is true. Therefore the code executes and prints out the first hello. Then, the value of i increases by one to 1.

Now, the condition 1 < 3 is still true, so the code executes. This goes on until the value of the counter variable is 3. Once the condition is 3 < 3 which is false. The loop terminates and three Hellos get printed.

Do-While Loop

Syntax of Do-While Loop:

void main(){
   
   // initialize counter variable
   do {
      // code;
      // increment/decrement;
   } while(condition);

}

How the Do-While loop works:

Initialize counter – Execute code – Increment – Condition check.

  1. The counter variable will be initialized outside the do-while block and the code block will be executed regardless of the condition for the first time.
  2. Then, the condition will be checked. If it’s evaluated to true, the loop will proceed to the next iteration.
  3. The iterations will continue until the condition is evaluated as false.

Note: The code block in the do-while loop is executed at least once.

Example:

void main(){
   int i = 0;
   do {
      print ("Hello");
      i++;
   } while (i<5);
}

Output:

Hello
Hello
Hello
Hello
Hello

The code is executed for the first time and then the counter variable is incremented by one. The loop then checks the condition 1 < 5. Since this is true, the loop will proceed to the next iteration.

In the next iteration, the counter variable is incremented by one. The loop then checks the condition 2 < 5. Since this is true, the loop will proceed to the next iteration. This will continue until the value of the counter variable is 5. This time the condition check 5 < 5 will be evaluated as false, so the loop ends after printing 5 Hellos.

Other key concepts

Break keyword

We use the break keyword to forcefully end a loop. It comes in handy when you want a partial output or to terminate the loop when a certain condition is met.

Example:

void main(){
 for (int i = 1; i<=10; i++){
    print ("Hello");
    if(i >= 6){
       break;
    }
  }
}

Output:

Hello
Hello
Hello
Hello
Hello
Hello

This code will terminate the loop after printing six Hellos because of the break statement.

Continue keyword

We use the continue keyword to skip some code and proceed to the next iteration.

Example:

void main(){
 for (int i = 1; i<=8; i++){
    if(i == 5){
       continue;
    }
    print (i);
  }
}

Output:

1
2
3
4
6
7
8

In the example, when i becomes 5, the loop is forced to the next iteration, thus skipping the print statement.

Real project Applications of loops

Here are some positive and negative applications of loops:

  • Writing a Music Player: A music player has a loop that enables it to play from one song to the next systematically.
  • Cycling through values: Loops are used to print out values in an extensive list. For example, the names of students in a school.
void main(){
   List grade_one_students = ["John", "Mark", "Alex"];
   for(String student in grade_one_students){
      print(student);
   }
}

Output:

John
Mark
Alex

It loops over all the elements stored in the list and prints them out.

  • Create computer viruses: Malicious programmers use loops to create computer viruses by using the While loop and embedding it to software downloads. If we write a while loop without the increment or decrement counter variable, it creates a never-ending loop which leads to unnecessary storage and memory consumption on devices. This causes the devices to crash or behave abnormally.

Caution: DO NOT RUN THIS CODE!!!

void main(){
   int i = 0;
   while(i<3){
      print("Hello");
   }
}

The code will print out an endless string of the word Hello. Note that we are not incrementing the counter variable.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More