Do-while Loop in Flutter

Do-While  loop first executes the statements and then checks for the condition. If the condition is true it will keep executing and if the condition is false the loop will terminate.Dart do while loop executes a block of the statement first and then checks the condition. If the condition returns true, then the loop continues its iteration. It is similar to Dart while loop but the only difference is, in the do-while loop a block of statements inside the body of loop will execute at least once.

A condition is evaluated either Boolean true or false. If it returns true, then the statements are executed again, and the condition is rechecked. If it returns false, the loop is ended, and control transfers out of the loop.

Let's understand the following example.

Example:

void main() {  

int i = 10;  

print("Dart do-while loop example");  

do{  

        print(i);  

        i++;  

}while(i<=20);  

print("The loop is terminated");  

}  

Output:

Dart do-while loop example

The value of i: 10

The value of i: 11

The value of i: 12

The value of i: 13

The value of i: 14

The value of i: 15

The value of i: 16

The value of i: 17

The value of i: 18

The value of i: 19

The value of i: 20

The loop is terminated

 

Explanation -

In the above code, we have initialised the variable i with value 10. In the do-while loop body, we defined two statements.

In the first iteration, the statement printed the initial value of i and increased by 1. Now the value of i becomes 11 and then we checked the condition.

The condition is, the value of i must be less than or greater than the 20. It matched with the condition and loop moved to the next iteration. It printed the series of numbers 10 to 20 until the condition returned false.


Advertisements