I have to write a program that calculates the avg, min, and max. The program runs fine, but when a user decides he doesn't want to enter any scores (enter: -1) in the beginning it still tries to calculate the avg,min and max.

I need the program to end w/o trying to calculate the mean, etc if the user enters -1 for the first value.

Thanks in advance.

int main()
{
	double score[75];
	int x = -1;
	double total = 0;
	double min = 101;
	double max = -1;
	do
	{
		x++;
		cout << "Please enter a score (enter -1 to stop): ";
		cin >> score[x];

		if (score[x] < min)
		{
			if (score[x] != -1)
				min = score[x];
		}
		if (score[x] > max)
		{
			max = score[x];
		}	
	} 
	while (score[x] != -1);
	for (int y = 0; y < x; y++)
	{
		total += score[y];
	}
	cout << "Average is " << (total / (double)(x)) << endl;
	cout << "Highest is " << max << endl;
	cout << "Lowest is " << min << endl;
}

Check the input immediately after reading it in and break out of the while loop right there if it's -1.

ETA: Or, rather, return immediately...I wasn't paying attention to where you do the calculations.

ETA2: You'll also have to make a flag to tell if you've read in any good values. Then, if(input == -1 AND goodValues == true) return;

Check the input immediately after reading it in and break out of the while loop right there if it's -1.

ETA: Or, rather, return immediately...I wasn't paying attention to where you do the calculations.

ETA2: You'll also have to make a flag to tell if you've read in any good values. Then, if(input == -1 AND goodValues == true) return;

I tried using a break with if statements with no luck...I came here as a last resort. Can anybody enlighten me?

You don't need a break. Read my edits, particularly #2.

change your do-while loop

do
	//..
	while (score[x] != -1);

to while loop:

while (cin >> score[x] && score[x]!=-1) {
//...
}

Some other small changes will be necessary as well (x variable starts from zero and it should incremented at the end of the loop).

The calculations aren't done in the loop, they're done right as the program is exiting.

just a simple if statement will do before the calculation.

if input is -1 then return 0 
else carry on with the calculation.

just a simple if statement will do before the calculation.

if input is -1 then return 0 
else carry on with the calculation.

Isn't -1 also the value to tell it that you're finished entering numbers? You can't just go exiting the program just because a -1 was entered; if there was good input before the -1 you need to do the calculations on them.

Check the value of 'x'.

if (x!=0) {
        cout << "Average is " << (total / (double)(x)) << endl;
        cout << "Highest is " << max << endl;
        cout << "Lowest is " << min << endl;
	}
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.