Dart for LoopDart for loop is used when we familiar with the number of execution of a block of code. It is similar to the C, C++, and Java for loop. It takes an initial variable to start the loop execution. It executes a block of code until it matches the specified condition. When the loop is executed, the value of iterator is updated each iteration, and then the test-expression is evaluated. This process will continue until the given test-expression is true. Once the test-expression is false, the for loop is terminated. Dart for Loop FlowchartSyntax:
Let's understand the following example. Example 1: Output: 1 2 3 4 5 6 7 8 9 10 Explanation: In the above example, we have initialized an integer variable i as initial value. We have assigned 1 to the variable and in the conditional part, we have defined the loop executed until value of i is smaller or equal to 10. Each time the loop will be iterated it will be increased value by 1. In the first iteration of a loop, the value of i is incremented by 1 and it will become 2. Now the condition is rechecked if condition is true, then the loop will be moved on next iteration. The iteration of the loop will continued until the value becomes 10. We can skip the initial value from the for loop. Consider the following example. It will give the same output as previous code. Also, we can skip the condition, increment, or decrement by using a semicolon. Nested for LoopThe nested for loop means, "the for loop inside another for loop". A for inside another loop is called an inner loop and outside loop is called the outer loop. In each iteration of the outer loop, the inner loop will iterate to entire its cycle. Let's understand the following example of nested for loop. Example - Output: 1 * 0 = 0 1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 1 * 4 = 4 1 * 5 = 5 2 * 0 = 0 2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10 Let's understand the working of nested for loop. Example - 2 Understand the inner loop cycle Output: Outer loop iteration : 1 i = 1 j = 1 Outer loop iteration : 2 i = 2 j = 1 i = 2 j = 2 Outer loop iteration : 3 i = 3 j = 1 i = 3 j = 2 i = 3 j = 3 Outer loop iteration : 4 i = 4 j = 1 i = 4 j = 2 i = 4 j = 3 i = 4 j = 4 Outer loop iteration: 5 i = 5 j = 1 i = 5 j = 2 i = 5 j = 3 i = 5 j = 4 i = 5 j = 5 Observe the above code, we have defined the working of the inner loop. The inner loop will be repeated for each iteration of the outer loop. Next TopicDart for..in Loop |