please explain this code to me

`

  main()
    {
    int u,i;
    for (u=1;u<=5;u++)
    {
    for (i=1;i<=u;i++)
    cout<<i<<"\t";
    cout<<endl;
    }
    }    






OUTPUT:
1
1    2
1    2    3
1    2    3    4
1    2    3    4    5

explain that how two loops are controlling this output someone explain it step by step how row by row output is obtained...for example in 3rd row when i=3 and we are couting "i" so tell me how 1 and 2 will also come with 3...i mean if cout "i" only then the output should be 3 only but i obtained output 1 2 3 how similarly for 4th and 5th row?????

Recommended Answers

All 8 Replies

In the third row u = 3 not i
At that moment line 6 of the code reads for (i=1;i<=3;i++) and i starts being 1. So 1 2 3 gets printed, the i-for loop finishes and u will become 4. Hope it clears things out. :)

Try changing 'u' to be 'row' and 'i' to be 'column' the code may make more sense.

commented: exellent idea +14

You have used 2 for loops. One with the variable 'u' and other with variable 'i'. The loop with the variable 'u' controls the row output and the one with 'i' controls column output.
step by step process is given below
1. When outer loop iterates for first time, value of 'u' is 1. Then the inner loop(the one with variable i) is executed. Here 'i' starts with value 1 for every iteration of outer loop. So for each iteration of the outer loop, the inner loop executes as many times as the value of 'u'. So in the 3rd row( i.e the 3rd iteration of outer loop), u=3. So values of i from 1-3 will be printed on the screen.

thanx alot all of you i got it...thanx again

helpful answer

Which explanation was the best?? Was it mine..

Or you could just be happy that mr.unknown learned something...

please tag it as solved

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.