How do I test a loop midway, save the answer, and output it at the end?

For instance, for this program, I need to determine when the total number is over 500, then display the answer after the table is displayed. Here is the code:

int main()
{
const int SIXTEEN = 16;
const int MAX = 500;
int adults = 1;
int noCages;
int babies = 0;
int total = 1;
int month = 1;

cout << "\nA table of rabbit populations, in pairs, for 15 months.";
cout << "\nMonth\tAdults\tBabies\tTotal";

while (month < SIXTEEN)
{

cout << "\n" << month << "\t" << adults << "\t" << babies << "\t" << total;

adults = babies + adults;
babies = adults - babies;
total = adults + babies;
month++;

}

system("PAUSE");
return 0;

}
I assume the loop need to be determined when total is over 500, and answer is the number hold in total after the loop?

You could add a condition to your loop (while (month < SIXTEEN && total <= MAX), or use a break inside an if-statement (I recommend you the first solution).
After the loop, total still holds his value and so it can be used to ouput the answer.
Topic archived. No new replies allowed.