While Loop in Flutter

While loop is usually used when we don’t know how many times the loop will actually execute at runtime.The while loop executes the block of code until the condition is true. While loops evaluate the condition before the loop runs.

The while loop executes the instructions each time the condition specified evaluates to true. In other words, the loop evaluates the condition before the block of code is executed.

 

Example

void main() {

  int a=0;

  

  while (a<5){

    print("Dart");

    a++;

  }

}

 

OutPut

Dart

Dart

Dart

Dart

Dart

 

Example

void main() { 

   var num = 5; 

   var factorial = 1; 

   

   while(num >=1) { 

      factorial = factorial * num; 

      num--; 

   } 

   print("The factorial  is ${factorial}"); 

The above code uses a while loop to calculate the factorial of the value in the variable num.

The following output is displayed on successful execution of the code.

Output:

The factorial is 120


Advertisements