For loop sets initial value for variable, condition and modification in one line.
varName
is initalized with value of start
.
The loop repeats until varName
reaches value of end
.
Each iteration adds step
value to varName
.
step
is optional parameter. If not specified the step of the loop is 1.
Let's have a program that prints each number from 1 to 10.
Output:
x
is initialized as 1.
The loop ends when x reaches value of 11.
Each iteration of the loop increments x
by 1 since no step is specified.
Let's proceed with a program that prints each number in the range 0 - 50 that is divided by 5:
Output:
The last parameter of range
specifies the step of the loop.
If we replace 51 with 50, then the last printed number will be 45.