Iteration Statements

Iteration Statements :

Iteration Statements allow a set of statements to be executed repeatedly until a required condition is not fulfilled.
Every loop statements has following elements as given :1. Initialisation expression : Here control variables are initialised. They are executed once before the beginning of the loop.
2. Test Expression : Its truth value decides whether the loop body will be executed otherwise loop will be terminated.
In an entry controlled loop it is evaluated before entering into a loop and in exit controlled loop it is evaluated before exiting from loop.
3. Update Expression : It changes the value of loop control variables.
4. Body of the loop : Statements that are to be executed in a loop.

Firstly, initialisation expression is evaluated, then, test expression, then body of loop and at last update statement

for Loop :

It is an entry controlled loop and the easiest to understand and implement.

Syntax :

for(initialisation  expressions; test expressions; update expressions)
{
:
body of the loop
:
}

If a for loop executes only once, it will terminate only when the value of its loop variable will cause a false condition.

Optional expression : Initialisation expression, test expression and update expressions are optional i.e. one or all of it can be skipped like if we have already initialised loop variables then Initialisation expression can be skipped.

Infinte loop using for loop : By removing the test expression infinte loop can be created.

Empty loop: The one which doesn’t contain any statement or a null statement only(;).

while Loop :

It is  an entry controlled loop.

Syntax :

while(test expression)
loop-body

Loop control variable can be initialised before the loop begins and can be updated in loop body.

do-while Loop:

It is an exit controlled loop i.e. test expression is evaluated before exiting loop body and loop body is executed atleast once even if the test expression is false.

Syntax :

do
{
body-of-loop
}
while(test-expression);

  • For loops are appropriate where we know in advance how many times the loop will execute and while and do-while are used where we do not know beforehand how many times the loop is to be executed.
  • do-while is used where loop body is executed atleast once irrespective of the test expression being true or false.

Leave a Reply

Your email address will not be published. Required fields are marked *