In: Computer Science
Do the following lab by while or Do-while loop.
question: Write a c++ program that asks students to enter 3 valid grades and then calculate the average and print it. if the user enters the invalid grade you should print the error message and get the new grade.
Hint1: each time your program ask the following question: "Do you want to calculate another average?" and if the answer to this question is "Y" or "y" then you should continue.
Hint2: this class at least has one student.
Hi this is the code,
//Consider highest grade is 10.taking grades out of 10.
#include <iostream>
using namespace std;
int main() {
int i = 0,gr[3],grade,avg,sum; //grade for acceptng each grade and gr is an array to store 3 grades.
char ch; //for user choice(y/Y)
do{
i=0;
sum=0;
while(i<3){
cout<<"Enter a grade(<=10): "; //asking for input from user.
cin>>grade;
if(grade<=10 && grade>0){ //check if its valid or not.
gr[i]=grade;
sum+=gr[i]; //sum for adding the grades.
i++;
}else{
cout<<"Not valid, please enter a valid grade. "<<endl; //error message.
}
}
avg=sum/3; //calculating the average.
cout<<"Your average is: "<<avg<<endl;
cout<<"Do you want to calculate another average? ";
cin>>ch; //again asking user for calculating average.
}while (ch == 'y' or ch=='Y'); //check if its yes.
return 0;
}
Happy Coding.
PLEASE GIVE A THUMBS UP IF IT WAS HELPFUL AND LEAVE A COMMENT FOR ANY QUERY.
THANKS.