Dart for Loop Tutorial With Examples

0
3706
dart for loop tutorial
dart for loop tutorial

Loop is used to execute a set of statements multiple times. In this tutorial, we will explor dart for loop with some examples. Loops are called iterators and in Dart, we have three kinds of iterators.

This tutorial is all about for loop iterator. For loop contains an initializer, a condition and an incremental/decremental. The syntax of for loop in dart looks like this.

  
 
for (Initialization; Condition; Increment/Decrement) {
  // code block to be executed
}
   
  • Initialization is executed only once. The very first time when the for loop starts.
  • Condition is checked every time. If the condition satisfies the loop code block will be executed.
  • Increment/Decrement is executed every time after the code block execution and the value of initialized variable changes according to incremental/decremental rule.

Dart for Loop Example

Using the given syntax let’s print the first 10 number. We have a variable i which is initialized with 1, a condition which is ‘the value of the variable should be smaller or equal than 10’ and finally a variable incremental which increments the value of i by 1.

  
 void main() {
  for (var i = 1; i <= 10; i++) {
    print(i);
  }
}  

The generated output is

  
1
2
3
4
5
6
7
8
9
10 

Let’s move one step further and perform some mathematical operations in loop. Let’s print even number from 1 to 10 using a for loop in dart.

  
void main() {
  for (var i = 1; i <= 10; i++) {
    if (i % 2 == 0) print(i);
  }
}

We are simply checking if the i is divisible by 2 or not. Which is actually definition of even numbers. The result on our console is

  
2
4
6
8
10

In the next example print the numbers from 1 to 10 but in reverse order. How will you write the code? Solution is simple.

  
void main() {
  for (var i = 10; i >= 1; i--) {
    print(i);
  }
}

Code will generate the following results.

  
10
9
8
7
6
5
4
3
2
1

Loops can be fun 😀 Write a loop without Initialization,Condition and Increment/Decrement statments. Something like this

  
void main() {
  for (;;) {
    print('This is crazy');
  }
}

Please do share your output. I am waiting. Hint the code is perfectly fine.

LEAVE A REPLY

Please enter your comment!
Please enter your name here