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
iwith an initial value - add
Whilewith conditioni <= end - assign
i = i + stepat the end of While
Let's write the same program as before, print the first 5 numbers:
- declare a
Forloop with variable namei - set
istart value to1 - set
iend value to5 - set
stepto1 - output
iinForbody
We achieved the same result, but with a lot less code.
Plus, it is more readable than before!