Introduction
Loops are used to perform a set of operations that need to be repeated continuously for a given number of times. These are one of the fundamental operations that one needs to learn while learning any new programming language.
New to Dart? Don't worry. We got you all covered. Feel free to navigate to the blog Dart SDK Installation and Environment Setup on the Coding Ninjas Website to set up the Dart SDK on your system if you have not already done so.
For loops
For loops in Dart are similar to those in Java and C. They are used to perform an operation a fixed number of times. The following is the syntax of the for loop in Dart.
for(initialization_exp; condition_check; test_expression){
// Write all the operations/statements here that need to be looped
}
The flow of the code goes as follows. First of all, the initialization expression is executed, and this expression is executed only once for a loop. After that, the control moves to the condition check expression. If the condition check expression satisfies, then we move to the loop's body. The loop's body contains all the code whose execution needs to be repeated. After executing the body, the control flow moves towards the test expression, where some operation is performed on the looping variable. Again the code moves towards the condition check expression, and if the condition satisfies, it enters the loop, and the cycle continues. The breaking out point from the loop comes when the condition check expression fails. In such a scenario, the execution flow jumps out of the loop and goes to the line written just after the loop. The following is a sample program to demonstrate the use of for loops in Dart.
Code:
void main() {
for (int i = 0; i < 5; i++) {
print('Hello Ninja number ${i + 1}');
}
}
Output:
Hello Ninja number 1
Hello Ninja number 2
Hello Ninja number 3
Hello Ninja number 4
Hello Ninja number 5
You must have guessed the control flow by now. First of all, we executed the initialization statement of the loop where we declare a looping variable named i and initialize its value to zero. After that, we check the condition, i < 5. Currently, we have the value of i as zero, this condition satisfies, and we enter the body of the loop, where we encounter a simple print statement. The print statement prints the following line on the terminal.
Hello Ninja number 1
After that, we move the expression i++, where we increment the value of i from 0 to 1 and again perform the condition check. Again i < 5 (1 <5), so we enter the body of the loop and execute the print statement. This continues until the statement i++ makes the value of i equal to 5. When the variable i takes the value 5, the condition check i < 5 would fail, and we will exit the loop.




