Short question

Hey everyone, I have a short question.
I'm trying to learn some basics, so I picked up a book and started reading :D I came to the chapter about nesting, and found the following bit of code:

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// The first, outer loop
cout << "This program sums multiple series\n"
<< "of numbers. Terminate each sequence\n"
<< "by entering a negative number.\n"
<< "Terminate the series by entering \n"
<< "two negative numbers in a row.\n";

int accu;
do
{
// start enterin the next sequence
// of numbers
accu = 0;
cout << "Start the next sequence\n";

// loop forever
for (;;)
{
// fetch another number
int value = 0;
cout << "Enter the next number: ";
cin >> value;

// if it's negative
if (value < 0)
{
break;
}

// If not, add the number to accu

accu = accu + value;
}

cout << "The total for this sequence is " << accu << endl;
}
while (accu != 0);

cout << "Thank you!" << endl;

system("PAUSE");
return 0;
}


If works exactly as described. It sums up sequences of numbers, which can be ended by entering a negative number. Then it lets you sum up another sequence.

What I don't fully understand is how terminating the series works. According to the program itsels, you need to put in two negative values in a row, and while it works, I don't really know why. Does it have to do with 'accu' resetting to a value of 0? Because the loop should repeat so long as accu =! 0. How does this work exactly?

Much appreciated!
Greye
It sets accu to 0 at the start. And if the first value you type in is negative, it never adds to accu. So then it gets to the end of the outer part, accu is equal to zero, so it doesn't loop again and thus exits the loop. Done.

If the very first number you entered into the program was negative, it would exit immediately.
Topic archived. No new replies allowed.