Assignment help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
while (grade<=100 && grade>=0)
{
        cout<<"Grade: "<<endl; 
	cin>>grade; 
	counter++;
	sum+=grade;
}

if (grade>100 || grade<=-2) 
{
	cout<<"Invalid Grade."<<endl;
	cout<<"Grade: "<<endl; 
	cin>>grade; 
	counter ++;
	sum+=grade;
}

if (grade = -1) 
{
        sum++;
	counter--;
	average = sum/counter; 
        cout<<"Average = "<<average<<endl; 
} 


How can I re write the code to prevent it from adding the grades over 100 and/or negative grades to the sum and not changing the count?
Last edited on
Have you ever used a do-while loop? This would really help for what you are trying to do. Here's a link for using do-while loops: http://mathbits.com/mathbits/compsci/looping/dowhile.htm
Basically, here's what you'd do:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
do
{
    // Prompt user for a grade and get input.
    if(grade < -1 || grade >= 100)
    {
        // Optional: Display an error (eg. cout << "invalid grade" << endl;)
        continue;// This will make the computer go back to the beginning of the loop and re-prompt the user for a grade.
    }
    if(grade != -1)
    {
        sum += grade;
        counter++;
    }
} while(grade != -1)


Hope that helps.
You were right!! Do while loop worked!
I didn't know it would make the program go back to the beginning of the loop and re prompt the user. Thank you!
Topic archived. No new replies allowed.