For loop sets condition variable initialization and modification on one line.
initialization - sets variables used in the loop (like i = 0
)
condition - Until when the cycle will keep on executing. Like i <= 10
.
modification - could avoid infinite loops (like i++
).
Let's have a program that prints each number from 1 to 10.
Output:
The initializationi = 1
performs first - before loop's iterations.
i++
executes in the end of every iteration.
An infinite for-loop has a condition that's always true or it's unset.
Let's look at the following example
Output:
Since condition is not specified the loop repeats infinitely.
There is more than 1 way of defining infinite loop.
Output:
In this case the only segment that's not specified is the condition therefore the cycle doesn't end.