Iteration Statements

Image result for c++ logo

These type of statements gets executed again and again based on a test condition i.e these are the statements which executes until the given test condition is true. There are three types of loop in C++ :
1. for loop
2. while loop
3. do-while loop (also known as exit control loop ).

All the above listed loop consist of four parts :
1. Initialization expression
2. Test expression
3. Update expression
4. Loop body

Lets discuss the syntax and working of each.

1. FOR LOOP
syntax:
for (initialization expressiontest expressionupdate expression)
     {
         loop body
     }
NOTE: REMEMBER THE SEMICOLON BETWEEN THREE EXPRESSIONS.

example:

working:
+ First declare a variable to hold a value. The declaration can be done inside the for loop as shown above or outside it. In above example we declare an integer variable and at the same time we initialize it to hold an integer value. 
+ Loop variable i takes its first initial value as 0.
+ Test condition is evaluated (whether 0 is less than 50) ,if its true then an entry inside the loop is given and the loop body gets executed.
+ After executing loop body, program control transfer to update expression which changes the value of loop variable again.
+ Then the test condition is again evaluated with the new value of loop variable, if its true then loop body again executed and this cycle continuous until the test condition become false. If false then that will be exit criteria for the loop.
+ Note: both postfix and prefix operator works in same way inside the loop, so you can use anyone, both ++i and i++ are same.
+ The above example will print the numbers from 0 to 50 line by line.

flow chart for FOR LOOP:

2. WHILE LOOP
syntax:
initialization expression
while (test expression)
{
     loop body
     update expression
}

example:

working:
+ Same as FOR LOOP.
+ The initialization of variable done outside the loop unlike FOR LOOP.

flow chart for WHILE LOOP:

3. DO-WHILE LOOP ( also known as exit control loop)
syntax:
initialization expression
do 
{
   loop body
   update expression
}
while (test expression) ;
NOTE: REMEMBER THE SEMICOLON AT THE END OF LOOP.

example:

working:
+ Same as FOR and WHILE LOOP.
+ The initialization of variable done outside the loop unlike FOR LOOP.
+ Unlike FOR and WHILE LOOP the test condition is checked only at the end in DO-WHILE LOOP, and for that reason it is also known as exit control loop.

flow chart for DO-WHILE LOOP:

INTERESTING FACT:

If all the expression of a FOR LOOP left empty then in that case it will act as an infinite loop, which will never terminate because when the expression is empty, it is assumed to be true by the compiler and the loop keep executing until you press Ctrl+C.
example:  
for ( ; ; )
     {
         cout << "This loop will never terminate" << '\n';
     }
output:


















Comments

Popular Posts