Program to drop lowest score and calculate average.

I have already started the program, the only issue is that I cannot get it to work. How can I improve my code?
Prompt:
Using the C++ while loop or the do – while loop (your choice) write a program that does the following:
Calculate the average of a series of homework grades (0 - 100) entered one at a time. In this case the lowest score will be dropped and the average computed with the remaining grades.
For example suppose you enter the following grades: 78, 85, 81, 90, 88, 93 and 97.
The average will be computed from the 6 grades 85, 81, 90, 88, 93 and 97. The low score of 78 will be dropped.
Output each grade (you can write it back out to the screen as each grade is entered), the dropped grade and the final average.
Run your program and show the output for the following two test cases:
CASE 1: Input grades 78, 85, 81, 90, 88, 93 and 97.
CASE 2: Input grades 75, 80, 83, 86, 90, 93, 87 and 77.

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
  #include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main(void)
{
    double average, grade, low;
    int i = 0;
    while(i<8)
    {
        cout << "CASE 1: input grades" << endl;
        cin >> grade;
        if (grade > 0 && grade<100)
        {
            average += grade;
            if (grade < low)
            low = grade;
            i++;
        }
    }
    average -= low;
    average = average / 7;
    cout <<"Average:" << average << endl;
    cout << "Lowest score dropped" << endl;
    return 0;
    
}
You never initialised either average or low.

Your examples also have unequal numbers of grades (the first has 7, the second has 8). So I suspect that should be an input parameter.

Please note that "cannot get it to work" is not a helpful explanation of what is wrong.
Last edited on
Possibly (changed as per lastchance's comment below):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

int main()
{
	constexpr int maxgrade {100};
	int total {}, grade {}, low {maxgrade}, cnt {};

	std::cout << "Input grades (0 - " << maxgrade << ") (-ve to finish): ";

	while ((std::cin >> grade) && (grade >= 0))
		if (grade > maxgrade)
			std::cout << "Grade greater than " << maxgrade << '\n';
		else {
			total += grade;
			++cnt;
			if (grade < low)
				low = grade;
		}

	std::cout << "Average: " << (total - low) / (cnt - 1.0) << '\n';
	std::cout << "Lowest score dropped: " << low << '\n';
}



Input grades (0 - 100) (-ve to finish): 75 80 83 86 90 93 87 77 -1
Average: 85.1429
Lowest score dropped: 75

Last edited on
Average: 74.5
Lowest score dropped: 75

That's a tad unlikely.

If you drop a score then you reduce cnt by 1.
Last edited on
Thanks :) Whoops....!

Above program changed...
@lastchance my bad, I meant to say I got stuck in an infinite loop.
Topic archived. No new replies allowed.