In this part, we are learning about how to implement loops in the Dart language. In the previous post, we already looked at how to implement For and For-each loop.
We are going to learn how to implement while and do-while loop in dart.
On a given Boolean condition, the while loop controls the flow and repeatedly executes the value. It loops through a block of code, as long as the specified condition is true.
The General Syntax:
Consider this simple example to understand the structure:
while (condition) {
// code block to be executed
}
Here’s a simple example that prints out from 0 to 10
main(){
int x = 0;
while (x <= 10) {
print("The output: ${x}");
x++;
}
}
You can see the difference between the for and while loops.
Note: Be careful about handling the while loop. Since a while loop evaluates the condition before the loop, you must know how to stop the loop at the right time before it enters into infinity.
Example:
To understand more easily we are going to implement Factorial of number in Dart and that too using while loop.
main(List<String> arguments) {
var num = 5;
var factorial = 1;
print("The value of the variable 'num' is decreasing this way:");
while(num >=1) {
factorial = factorial * num;
num--;
print("'=>' ${num}");
}
print("The factorial is ${factorial}");
}
The while loop evaluates the condition. Since the value of the variable num is 5 and it is greater than or equal to 1, the condition is true. So, the loop begins. As the loop begins, we have also kept reducing the value of the variable num; otherwise, it would have entered into an infinite loop.
The value of the variable 'num' is decreasing this way:
'=>' 4
'=>' 3
'=>' 2
'=>' 1
'=>' 0
The factorial is 120
Do-While Loop in Dart
Lets try to implement the same code using a do-while loop
main(List<String> arguments) {
var num = 5;
var factorial = 1;
do {
factorial = factorial ∗ num;
num--;
print("The value of the variable 'num' is decreasing to : ${num}");
print("The factorial is ${factorial}");
}
while(num >=1);
}
We have slightly changed the code snippet so that it will show the reducing value of the variable, and at the same time, it will show you how the value of the factorial increases.
The value of the variable 'num' is decreasing to : 4
The factorial is 5
The value of the variable 'num' is decreasing to : 3
The factorial is 20
The value of the variable 'num' is decreasing to : 2
The factorial is 60
The value of the variable 'num' is decreasing to : 1
The factorial is 120
The value of the variable 'num' is decreasing to : 0
The factorial is 120
Conclusion:
we have seen the most popular loops in Dart. Once you understand the pattern of loops, you can easily choose between for, while, and do-while.