Dart for Loop
Dart for Loop
Dart for loop is a control flow statement that allows you to repeatedly execute a block of code for a specific number of times or iterate over a sequence of elements. It is used when we know how many times a block of code will execute.
Dart for Loop
The syntax is the same as the C for loop. The general syntax of a for loop in Dart is as follows:
for (loop_initialization; loop_condition; incr/decr expression) {
// loop code to be executed
}
Loop Initialization
It is executed once before the loop begins. It typically involves initializing a loop control variable.
Loop Condition
It is evaluated before each iteration. If the condition is true, the loop body is executed. If it is false, the loop terminates.
Expression
It is evaluated after each iteration. It usually involves updating the loop control variable. The incr/decr is the counter to increment or decrement the loop variable.
The loop iteration starts from the initial value. The loop condition is checked after each iteration. The for loop will execute until false is returned by the given condition.
Example
Let’s see a basic for loop to print numbers from 1 to 10.
/* * For Loop demo Dart Program * Dart Tutorials - www.TestingDocs.com */ void main() { // Dart for Loop for (var i = 1; i <= 10; i++) { print(i); } }
In this example, the loop initializes i (the loop control variable) with the value 1 and executes the loop body as long as i is less than or equal to 10. After each iteration, i is incremented by 1.
for Loop is commonly used when you know the exact number of iterations or when you want to perform an action for each item in a collection.
—
Dart Tutorials
Dart tutorial on this website can be found at:
https://www.testingdocs.com/dart-tutorials-for-beginners/
More information on Dart: