+ 1
How would I solve this for loop? I am trying to get the value of the sum.
int sum =0; for(int i=0; i<5;i++) { for(int j=i-1; j>0; j--) { sum++; } }
16 Antworten
+ 3
Check out the comments at the bottom of the code:
https://code.sololearn.com/cSSEuIPyZTzi/?ref=app#cpp
I've reproduced the comments here:
Note, this is far harder than it looks to work out!
So don't be disheartened as a beginner.
sum = 0
i = 0
j = i - 1 = -1
for (int j = i - 1; j > 0; j--)
for (int j = -1; j > 0; j--) [code doesn't run inside this for loop this time]
sum = 0
i = 1
j = i - 1 = 0
for (int j = i - 1; j > 0; j--)
for (int j = 0; j > 0; j--) [code doesn't run inside this for loop this time]
sum = 0
i = 2
j = i - 1 = 1
for (int j = i - 1; j > 0; j--)
for (int j = 1; j > 0; j--) [code runs inside this loop once] ==> sum++
sum = 1
i = 3
j = i - 1 = 2
for (int j = i - 1; j > 0; j--)
for (int j = 2; j > 0; j--) [code runs inside this loop once] ==> sum++
sum = 2
for (int j = 1; j > 0; j--) [code runs inside this loop again] ==> sum++
sum = 3
i = 4
j = i - 1 = 3
for (int j = i - 1; j > 0; j--)
for (int j = 3; j > 0; j--) [code runs inside this loop once] ==> sum++
sum = 4
for (int j = 2; j > 0; j--) [code runs inside this loop once] ==> sum++
sum = 5
for (int j = 1; j > 0; j--) [code runs inside this loop once] ==> sum++
sum = 6
end of for loops.
+ 2
Here's the code running:
https://code.sololearn.com/cSSEuIPyZTzi/?ref=app
+ 2
You need to step through the code on paper. I'll try to explain in more detail. Give me some time.
+ 1
It depends what you mean by 'solve'. What are you trying to do?
+ 1
The sum of what?
+ 1
@xan thank you so much. do you know how it got to 6? like the loop pattern and how it increments etc....? thank you again!!
+ 1
okay thank you!!! I truly appreciate it! @xan
+ 1
@xan thank you, I totally understand now!!!!
+ 1
@Xan Wow thank you so much!!!! I really can't thank you enough!!! I truly have a full understanding now!
+ 1
No problem. I was stumped at first myself, even with 30+ years programming experience! In reality, this would be considered unprofessional code if seen in the wild, but it's a good training exercise.
0
for each iteration in the first for loop calculate all the values of the for loop inside.
Btw I think i-1 in the code =-1, so the second for loop wouldn't run.
0
because the first loop is true from the start do I increment it by 1 anyways? or what do I do?
0
and the second loop is false so it would not run... but it would loop through the first 1 making i=1 then go through the second loop and it will still be false. then make the 1st one 2 and once it hits the second loop it will then be true making the sum 1 ... I think I'm still confused can you explain it more? @akib
0
@xan I am trying to get the sum
0
the value of sum. @xan
0
e,m
z,c