-moz-user-select:none; -webkit-user-select:none; -khtml-user-select:none; -ms-user-select:none; user-select:none;

Thursday, 23 April 2015

Nested loops in C++

Hello and Asalam o Alikum. I hope you all are fine by the grace of Allah Almighty.

Today I here with one of the most important topics of C++,"Nested loops".

Nested Loops

A loop within another loop is known as nested loop or the body of a loop can itself contain a loop which is known as nested loop.
In nested loop, the inner loop is executed only when the outer loop is executed. If the condition in the outer loop becomes false, the inner loop will not execute at all.

Syntax

for(initialization;condition;increment/decrement )//outer loop
{
for(initialization;condition;increment/decrement)//inner loop
statement(s)
}
 
The source code of a simple "nested loop" program is given below:

Source code



Output


Explanation:

                      In the above example, the iteration for outer loop is from 0-7  and the iteration for inner loop is also from 0-7.

How the program works?

The value of outer loop is 1 in the start. As it is less than 7,so the condition becomes true. It will immediately moves towards the inner loop. The iteration in inner loop us from 0-7. So, it will display "01234567".It will again moves towards the outer loop.

Next time, the value in the outer loop becomes 2. As it is less than 7, so the condition becomes false. It will again moves towards the inner loop. The iteration in inner loop us from 0-7. So, it will display "01234567".It will again moves towards the outer loop.

This process continues until the value in the outer loop becomes 8. As 8 is less than 7, so the condition becomes false. As the condition in the outer loop becomes false, it will not jump towards the inner loop and the loop will terminate. 


No comments:

Post a Comment