Monday, December 15, 2008

nested loop

Nested loops-
Loops in loop is called as nested loop. A loop can be written in another loop. For example a for loop may contain another for loop which may again contain other for loops. The other loop can contain similar form.
Eg.
Void main()
{
Int x[2][2],y,z;
For(y=0;y<2;y++)
{
For(z=0;z<2;z++)
{
Scanf(“%d”,&x[y][z]);
}
}
Getch();
}
In the above program there are two for loops. The first for loop is for the row of the array and second for the column. When the first column is finished ie. When the second for loop is finished the loop ends. Then the first loop start for its second number. This again takes the control to the second loop which is again activated. This continuous till the outer loop exits. The nesting may have many for loops in it. The multi dimensional arrays need many nested for loop for storing values it it. For the nested loop the brackets are necessary for continuing the outside loop.the inner most loop continuous until the outer loop exits.
In the similar way the while loop may also contain a another while loop and a do…while may contain other do…while statements.
A for loop may also contain a while loop or a do while loop.

No comments:

Watch tv!