0

Please help me with this code!

Why does the Programm only stops when I write two negative numbers? Int sumSequence () { Int Accumulator = 0; for(;;) { Int value; Cout << "Next:"; Cin >> value; If (value < 0){ break; } Accumulator += value; } return Accumulator; } Int main () { for(;;) { Int sum = sumSequence() ; if (sum == 0) { break; } Cout << sum; }

7th Mar 2019, 10:02 PM
Kevin
Kevin - avatar
2 Answers
+ 2
You have a nested loop ( a loop inside a loop ), the loop inside main is effectively the outer loop and the loop inside the function is the inner loop. While you are entering non negative values you are incrementing the accumulator. When you enter a negative number you only break out of the inner loop and return a non zero value. This will not break out of the outer loop and the inner loop starts its cycle again with its accumulator reset to 0. Enter a negative value again and now this zero value is returned which terminates both loops. If you want to also break out of the outer loop the first time you should either replace break with return 0; or reset accumulator to 0 before you break in order to satisfy the sum == 0 check.
7th Mar 2019, 10:32 PM
Dennis
Dennis - avatar
0
Thank you very much!
7th Mar 2019, 10:38 PM
Kevin
Kevin - avatar