Loop
What is the value of n after the following nested loops?
1 2 3 4
|
int n = 0;
for (int i = 1; i <= 5; i++)
for (int j = 0; j < i; j++)
n = n + j;
|
I tested it out and the value was 20. But Im not sure how the process works.
i: 1
j: 0
n = 0 + 0
i: 2
j: 0
n = 0 + 0
j: 1
n = 0 + 1
i: 3
j: 0
n = 1 + 0
j: 1
n = 1 + 1
j: 2
n = 2 + 2
i: 4
j: 0
n = 4 + 0
j: 1
n = 4 + 1
j: 2
n = 5 + 2
j: 3
n = 7 + 3
i: 5
j: 0
n = 10 + 0
j: 1
n = 10 + 1
j: 2
n = 11 + 2
j: 3
n = 13 + 3
j: 4
n = 16 + 4
|
Thank you @xsimn! :)
Topic archived. No new replies allowed.