
For loop (programming)

Upgrade for more content
True or false? There are several ways to repeat code.
Lena has programmed her robot to give Maria and Leon chocolate. Maria improved Lena’s program and now, it does not need to be restarted again and again. This is what the pseudo code now looks like. While there are chocolates in the box, in other words, as long as the variable chocolates is larger than 0, the robot gives Maria and Leon chocolate. Maria has used a ‘while’ loop.
Lena knows a way to make the code even better. Since Lena knows that a newly opened chocolate box contains 10 chocolates, then this information doesn’t need to be input every time. Instead, she can use another type of loop, which will be repeated, iterated, 10 times. This kind of loop is iterated from a starting value to a final value for a variable. The instructions inside the loop are only performed when the variable is between its starting value and its final value.
She uses the variable name ‘i’ as in iterate. Lena’s pseudocode looks like this. For all values of the variable ‘i’, from a start value to a final value, the instructions inside the loop should be performed. In the instructions for the loop, Lena sets the start value as one. When the loop starts, the variable ‘i’ has the value 1.
She writes from 1. She wants the instructions in the loop to be performed 10 times. So, Lena writes 10 as a final value. Every time, the instructions in the loop are iterated, the variable ‘i’ should increase by 1. So, Lena sets the size of each step in her code as 1.
This is a 'for' loop and it is performed for all values from the start value 1 up to the final value 10. When the program used a while loop, an instruction was required inside the loop that reduced the number of chocolates by 1 each time, but when Lena uses a for loop, then that instruction is not needed. She can erase this part. The new pseudocode looks like this. Lena tests the for loop she has written.
When the for loop starts, the variable ‘i’ has the value 1. The instructions in the loop are performed and the program goes back to the top of the loop. Now, this part of the instruction is performed, increasing the value of the variable ‘i’ by one step. 1 plus 1 becomes 2. 2 is still between 1 and 10.
The instructions in the loop are performed again and the program goes back to the top of the loop. And once more, the value of ‘i’ increases by 1. Now, the value is 3. 3 is among all values of ‘i’ from 1 to 10 and then the loop keeps going when the variable ‘i’ has the value of 4, 5, 6, 7, 8, 9 and 10. When ‘i’ changes value to 11, then the value of the variable does not belong to all values from 1 to 10.
The loop ends and the program continues. In this case, no more instructions exist and the program ends. Let’s compare the ‘for’ loop with Maria’s ‘while’ loop. Lena has replaced three instructions with only one. Fewer instructions make the code easier to read.
A code becomes more elegant.