Dart Loop is used to run a block of code repetitively for a given number of times or until matches the specified condition.Dart supports the following type of loops.
Dart for loop
Dart for…in loop
Dart while loop
Dart do-while loop
Dart for loop
The for loop is used when we know how many times a block of code will execute. It is quite same as the C for loop.
The loop iteration starts from the initial value. It executes only once.
The condition is a test-expression and it is checked after each iteration. The for loop will execute until false returned by the given condition.
The incr/decr is the counter to increase or decrease the value.
Let's understand the following example.
Example :-
void main()
{
int num = 1;
for(num; num<=10; num++) //for loop to print 1-10 numbers
{
print(num); //to print the number
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Dart for… in Loop
The for…in loop is slightly different from the for loop. It only takes dart object or expression as an iterator and iterates the element one at a time. The value of the element is bound to var, which is and valid and available for the loop body. The loop will execute until no element left in the iterator.
Example :-
void main()
{
var list1 = [10,20,30,40,50];
for(var i in list1) //for..in loop to print list element
{
print(i); //to print the number
}
}
Output:
10
20
30
40
50
Dart while loop
The while loop executes a block of code until the given expression is false. It is more beneficial when we don't know the number of execution.
Example:-
void main()
{
var a = 1;
var maxnum = 10;
while(a<maxnum){ // it will print until the expression return false
print(a);
a = a+1; // increase value 1 after each iteration
}
}
Output:
1
2
3
4
5
6
7
8
9
Dart do…while Loop
The do…while loop is similar to the while loop but only difference is that, it executes the loop statement and then check the given condition.
Example -
void main()
{
var a = 1;
var maxnum = 10;
do
{
print("The value is: ${a}");
a = a+1;
}while(a<maxnum);
}
Output:
The value is: 1 The value is: 2 The value is: 3 The value is: 4 The value is: 5 The value is: 6 The value is: 7 The value is: 8 The value is: 9
Selection of the loop
The selection of a loop is a little bit difficult task to the programmer. It is hard to decide which loop will be more suitable to perform a specific task. We can determine the loop based on the following points.
Analyze the problem and observe that whether you need a pre-test loop or post-test loop. A pre-test loop is that, the condition is tested before entering the loop. In the post-test loop, the condition is tested after entering the loop.
If we require a pre-test loop, then select the while or for loop.
If we require a post-test loop, then select the do-while loop.