Hi there all! This is my first time on this forum, and I tried to solve this problem by other methods previously, but I haven't found a solution yet. In school, I am writing a program to find the average of a certain amount of grades. The number of grades is an input from the user, and the program is supposed to ask for grades ONLY until the number of times the loop executes equals the number of grades. My problem is that when I input 2 as the number of grades, the program asks me for 3 grades.
I know that we don't like homework questions on this forum, but my code is complete except for this problem and I will receive a failing grade this marking period if I don't fix this. Thank you!
This is my code:
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main()
{
int Average;
int Grades;
int Total;
int AmountGrades;
int Counter;
cout << "Enter amount of grades: ";
cin >> AmountGrades;
do
{
cout << "What is one of the grades? \n";
cin >> Grades;
Total=Total+Grades; // values CAN be = to 0 or 100
Counter++;
}
while (Counter<=AmountGrades);
cout << "The total is: " << Total << endl;
Average=(Total)/(AmountGrades);
cout << "The average of the grades is: " << Average << endl;
You should set counter to zero at the start of your program. I think your compiler automatically sets uninitialized variables to zero, as you aren't initializing counter. It asks for 3 grades because if counter is 1 in the beginning and you loop condition is counter <= amount, it will loop 2 times (once for counter = 1 and once for counter = 2), but as your counter is set to zero, it loops one extra time.