I am struggling with this program that wants to ask the user how many grades they wish to enter, have the user enter each grade, then determine the average of all the grades. I am stuck with getting the average to computer correctly... Can you guys check to see what I am missing in my code?
[highlight=Java]
int main()
{
//No Local constants
int counter = 0; //While Loop counter
//Local variables
int totalGrades; //Max number of loop executions
int runningTotal; //Running total of loop counter
int grade;
int average; //Average of grades
char endProgram; //Pause screen
/*************** Begin main Function Executables *****************/
//Clear the screen
system ("cls");
//Prompt user for number of grades they want to enter
cout << "How many grades would you like to enter? ";
cin >> totalGrades;
while (counter < totalGrades) //stop when counter equals value of totalGrades
{
runningTotal = grade + counter;
cout << "Please enter the next grade ---> ";
cin >> grade;
counter = counter + 1; // increase counter by 1
} //end while loop
average = runningTotal / totalGrades; //compute average
cout << average << " is the average of the grades entered." << endl;
That's what I figured as well.. I have been playing around and tweaking that formula for a few hours now. Am I supposed to set values for every grade the user inputs? If so, how can I do that?
What happens first time you enter the while loop? It assigns to runningTotal values of counter(which is 0) and value of grade which is... Actually it can be anything. There is no value in it before first run is completed.
Notice that I use counter++ rather than counter = counter + 1; it is an equivalent shortcut.
Also initialising your variables (setting them to equal something) is a very important concept in programming, and is the source of lots of errors. The best thing is to set them at the same time as declaring:
1 2 3 4 5
int totalGrades = 0; //Max number of loop executions
int runningTota = 0; //Running total of loop counter
//same thing for the others
I like the good names for your variables, and the description for what they mean - good stuff.
A further clue to fg109's & eraggo clues - it's in the wrong place.