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.
- FOR LOOP
- WHILE LOOP
- DO WHILE LOOP
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
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.