If you have a predetermined number of iterations for a block of code, opt for the for loop instead of a while loop.
|
Statement 1 is executed once before the code block is executed.
Statement 2 specifies the condition for executing the code block.
Statement 3 is executed after the code block has been executed, and it repeats every time.
The following example will print numbers from 0 to 4:
|
Statement 1 initializes a variable before the loop begins (int i = 0).
Statement 2 establishes the condition for the loop to execute (i must be less than 5). If the condition is true, the loop restarts; if false, the loop terminates.
Statement 3 increments a value (i++) each time the code block within the loop executes.
This example specifically outputs only the even numbers within the range of 0 to 10.
|