loop help!

Hi I'm having problems with a homework assignment. The task is to write a C++ program that allows the user to enter as many non-negative integers as they would like. When the user enters a negative number, stop collecting numbers and output to the console the largest and the smallest number entered (not counting the negative number).

I currently have it working except that my negative number is included in my lowest value. Please help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
using namespace std;

int main ()
{
   //variable initialization
   int number;
   int lowNum = 0;
   int highNum = 0;
	
   //loop
   do 
   {
        cout << "Please enter a number: " << endl;
	cin >> number;

	if ( number > highNum)
	highNum = number;

	if ( number < highNum)
	lowNum = number;

	if (number < lowNum)
	lowNum = number;
		

   } while (number >= 0);
		

   //display low/high num
   cout << lowNum << endl;
   cout << highNum << endl;
	

	return 0;
}
Last edited on
Add an if statement saying that if the number is negative then break out of the while loop.
Last edited on
the while part does that.
Hi, you need an extra if to wrap your statements.

1
2
3
4
5
6
7
8
9
10
11
do
{
    cout << "Please enter a number: " << endl;
    cin >> number;

    if (number >= 0)
    {
        if (number > highNum)
        ...
    }
} while (number >= 0);
@liuyang
Your method did work, but my low number is always zero, even if i didn't type zero.
Well it does work, only if you type in the higher number first.
I know the while loop does that, but since it's a do while loop it would count in the negative number first then exit out of the loop; that's what I was trying to get you out of.
I know. But i have to have it keep on repeating infinitly until the user enters a negative number. Then it HAS to stop and display the high and low number of the numbers entered (not including the negative number that was entered).
You can initialise the lower number to an impossible number first (say -1), and set it to the 1st input directly in your loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int lowNum = -1;    //here

do
{
    ...
    if (number >= 0)
    {
        if (lowNum < 0)
            lowNum = number;    // and here

        if (...)  // your other statements
    }
} while (...);
I was saying with mine that when you have entered a negative number it would go through and add it to the low number, which is not what you wanted to do. By adding the if statement stating that if the number was negative, then quit the while loop, it would be similar to the while loop doing so except with it adding the number to the lownumber variable.
Topic archived. No new replies allowed.