Do While Loop in Dart
Do While Loop
Do while loop is used to run a block of code multiple times. The loop’s body will be executed first, and then the condition is tested. The syntax of do while loop is:
do{
    statement1;
    statement2;
    .
    .
    .
    statementN;
}while(condition);
- First, it runs statements, and finally, the condition is checked.
- If the condition is true, the code inside {} is executed.
- The condition is re-checked until the condition is false.
- When the condition is false, the loop stops.
 Info
    Note: In a do-while loop, the statements will be executed at least once time, even if the condition is false. It is because the statement is executed before checking the condition.
Example 1: To Print 1 To 10 Using Do While Loop
void main() {
  int i = 1;
  do {
    print(i);
    i++;
  } while (i <= 10);
}
Run Online
Example 2: To Print 10 To 1 Using Do While Loop
void main() {
  int i = 10;
  do {
    print(i);
    i--;
  } while (i >= 1);
}
Run Online
Example 3: Display Sum of n Natural Numbers Using Do While Loop
Here, the value of the total is 0 initially. Then, the do-while loop is iterated from i = 1 to 100. In each iteration, i is added to the total, and the value of i is increased by 1. Result is 1+2+3+….+99+100.
void main(){
  int total = 0;
  int n = 100; // change as per required
  int i =1;
  
  do{
  total = total + i;
    i++;
  }while(i<=n);
  
  print("Total is $total");
  
}
Run Online
When The Condition Is False
Let’s make one condition false and see the demo below. Hello got printed if the condition is false.
void main(){
  int number = 0;
  
  do{
  print("Hello");
  number--;
  }while(number >1);
  
}
Run Online
Video
Watch our video on while loop in Dart.