7. Loops
Loops execute a block of code until some condition is met. The two most common types of loops are for
and while
. The jumps and conditional jumps that you have seen so far have been jumping forward. The loops jump backward. First, let's understand the functionality of a for
loop. The general form of a for
loop is shown here:
for (initialization; condition; update_statement ) { block of code }
Here's how the for
statement works. The initialization
statement is executed only once, after which the condition
is evaluated; if the condition is true, the block of code inside the for
loop is executed, and then the update_statement
is executed.
A while
loop is the same as a for
loop. In for
, the initialization
, condition
, and update_statment
are specified together, whereas in a while
loop, the initialization
is kept separate from the condition
check, and the update_statement
is specified inside the loop. The general form of a while
loop is shown here:
initialization while (condition) { ...