Jess_F
Jess_F

Reputation: 11

can't understand for nested loop

I am new to programming, I ran into this pattern problem which I am confused of the solution.

Output:

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Input(correct solution):

rows = 6

for i in range(rows):
    for j in range(i):
        print(i, end=' ')
    print('')

What I think the process of the code will be like:

In 1st iteration - i is 0; j is 0; print i; therefore, 0 is printed

In 2nd iteration - i is 1; j is 0, 1; the action is to print i; therefore, 1 is printed

In 3rd iteration - i is 2; j is 0, 1,2; the action is to print i; therefore, 2 is printed

I am sure my idea is wrong but can anyone point out what is wrong and correct me?

Thank you very much

Upvotes: 0

Views: 222

Answers (2)

well, i is the iteration for changing the number (0 to 5), j is the iteration for repeating this number "i" times. so:

In 1st iteration - i is 0; j is 0; 0 is printed 0 times (none)

In 2nd iteration - i is 1; j is 0-1; prints 1 one time

In 3rd iteration - i is 2; j is 0-2; prints 2 two times

In 4th iteration - i is 3; j is 0-3; prints 3 three times

Upvotes: 1

Jack Deeth
Jack Deeth

Reputation: 3357

welcome!

for i in range(rows):
    for j in range(i):

The first time through, i is 0, so for j in range(i): runs zero times.

The second time, i is 1, so for j in range(i) prints 1 1 time.

The third time, i is 2, so for j in range(i) prints 2 2 times… and so on.

Upvotes: 2

Related Questions