11 / 16

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 condition i <= 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 name i
  • set i start value to 1
  • set i end value to 5
  • set step to 1
  • output i in For body

We achieved the same result, but with a lot less code.
Plus, it is more readable than before!