Jan 5, 2012

Using Nested Loop

 Using Nested Loop

Nested Loop is using loop inside a loop like for loop is under for loop for example: 
for(int i=0;i<10;i++)
{for(int j=0; j<4; j++)
{cout<<i;}
}


Above code is use like that first i value is 0 then condition true and then second loop is run it run for 4 times then increment is done and i value is 1 now and condition is true so it run again means the i loop run for 10 times and in every time i loop run 4 time second loop runs so total 40 times loop Run.
Check out Example of Number Triangle

#include<iostream.h>
#include<conio.h>
//Using Nested Loop
int main()
{
for(int i=1; i<10; i++)  // i set to 1 and less than 10
{
    for(int j=0; j<i; j++) // j set to 0 and j less than i
    {
        cout << i;
    }
    cout << endl;
}

/* above code first i=1 and j=0 and it print 1 only one time because condition true that j < i (i=1) and new line 
then increment is done and i value is now 2 and then j =0 and j<2 so it print i value 2 time and new line
Similarly it continue till i < 10. Check the output
*/
getch();
}


OUTPUT






0 comments:

Post a Comment