Greatly appreciate if any one can help me with this small programming challenge for a newbie.

Write a program segment with a do-while loop that asks the user to enter a number.
The loop should keep a running total of the numbers entered and stop when total is greater than 300.

## All 8 Replies

Please post what you've tried so we can tell you where your error is. Welcome aboard

I really dont have a clue..this is as far as i could get.
thanks
jj

``````int main()
{

int num, total;

num = 0;
while (num <= 300);
{
cout << "Enter  a number: ";
cin >> num;
total += num;
num++;
}
return 0;
}``````

Write a program segment with a do-while loop

your program does not do that. You used a while loop, not a do-while loop. Otherwise the rest of your program looks ok.

I changed it to a do while loop. Not getting anywhere. My output is down below.

``````//PRE-PROCESSOR DIRECTIVES
#include <iostream>
using namespace std;

//MAIN FUNCTION
int main()
{

int num, total;

num = 0;
do
{
cout << "Enter  a number: ";
cin >> num;
total += num;
num++;

}while (num <= 300);

return 0;

}``````

//OUTPUT
/*
Enter a number: 2
Enter a number: 2
Enter a number:

*/

probably because you need to add a line between lines 15 and 16 that removed the '\n' (the Enter key) from the keyboard buffer. The easiest way to do that is to use ignore() method

``cin.ignore();``

There are cases where the above won't fix the problem, but if all you type after the digits is the Enter key then the above will work.

I tried it still doesnt work. i think the logic must be wrong. The loop should keep a running total of the numbers entered and stop when total is greater than 300

``````int main()
{

int num, total, x;

num = 0;
do
{
cout << "Enter  a number: ";
cin >> num;
cin.ignore();
total += num;
num++;

}while (num <= 300);

return 0;

}``````

//OUTPUT
/*
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number:

*/

The loop should keep a running total of the numbers entered

It does that

and stop when total is greater than 300

Look at the end of the do-while loop -- it is testing the wrong variable. Variable num just simply counts the number of entries made, so you would have to enter over 300 numbers before that loop stops. :-O The condition should be based on total, which is the sum of all previously numbers entered.

i finally got it work. had to make a couple of adjustments. thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.