please explain this code to me


    int u,i;
    for (u=1;u<=5;u++)
    for (i=1;i<=u;i++)

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?????

Edited by mr.unknown

3 Years
Discussion Span
Last Post by sanjulovers

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. :)


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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.