For loop
The For
loop is a bit more complex.
It is made of:
- loop variable name
- loop variable initial value
- loop variable end value
- step (increment), by how much the loop variable is incremented in each iteration
TheFor
loop replaces the following code:
- declare an Integer
i
with an initial value - add
While
with conditioni <= end
- assign
i = i + step
at the end of While
Let's write the same program as before, print the first 5 numbers:
- declare a
For
loop with variable namei
- set
i
start value to1
- set
i
end value to5
- set
step
to1
- output
i
inFor
body
We achieved the same result, but with a lot less code.
Plus, it is more readable than before!