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;
}

Dani AI

Generated

The symptom is that the sentinel (-1) is ending up in the data set and the program still uses the array-count as the divisor. In 's do/while version the index becomes 0 when the first entry is -1, the sum loop is skipped, and the code then divides by x (zero). That causes a divide-by-zero or NaN. Also, initializing min and max to magic numbers (101 and -1) hides the "no input" case. The quick fixes mentioned by , and (check if any good values were read, or return early) are correct; the more robust approach is to avoid storing the sentinel and to explicitly test for an empty data set before computing.

A simple, safer pattern:

  • read into a temporary variable,
  • stop on the sentinel without pushing it into your container,
  • if the container is empty after the loop, report "no scores" and skip calculations,
  • otherwise initialize min/max from the first real value (or use numeric_limits) and compute average/min/max.

Example using a std::vector (keeps logic simple and avoids fixed-size indexing):

#include <iostream>
#include <vector>

int main() {
    std::vector<double> scores;
    double value;
    while (std::cin >> value) {
        if (value == -1) break;   // do not store the sentinel
        scores.push_back(value);
    }
    if (scores.empty()) {
        std::cout << "No scores entered.\n";
        return 0;
    }
    double total = 0;
    double minv = scores.front();
    double maxv = scores.front();
    for (double s : scores) {
        total += s;
        if (s < minv) minv = s;
        if (s > maxv) maxv = s;
    }
    std::cout << "Average: " << total / scores.size() << '\n';
    std::cout << "Lowest: "  << minv << '\n';
    std::cout << "Highest: " << maxv << '\n';
}

Extra tips: if you must use a fixed array, keep a separate count (do not rely on the sentinel slot), or decrement the index after the loop only when you know a real value was stored. Validate input limits if -1 could be a valid score in some contexts. Always check bounds before writing into an array to avoid overflow.

Recommended Answers

All 8 Replies

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.