Hello, I have a query regarding c programming. I\'ll be very thankful ifsome one
ID: 3613262 • Letter: H
Question
Hello,
I have a query regarding c programming. I'll be very thankful ifsome one could help. I'm giving the program code below:
//Program that calculates average of student grades.
#include<iostream.h>
#include<stdlib.h>
main()
{
int sum=0, student=0, grade=0, numstudent=0, average=0;
cout<<"Please enter the number of studentsin the class: ";
cin>>numstudent;
cout<<" ******************************************************************************* ";
do
{
cout<<endl<<"Please enter the gradeof student in integer values: ";
cin>>grade;
if(grade<0)
{
break;
}
sum += grade;
student++;
}
while(grade>=0 &&student<numstudent);
cout<<" ******************************************************************************* ";
average = sum / student;
cout<<endl<<"The average of thestudents is: "<<average;
cout<<endl<<endl;
system("pause");
}
When I run this code in Dev C++. The program runs fine. It gives noerror with compilation of code and calculates the average perfectlyas I want it to. But the problem is that the code checks thecondition from the while loop after executing the do loop becauseits a do-while loop and loop executes at least once. What if I wantthe condition to be such that if the user put a value of grade asnegative number (eg: -1). The loop shouldn't execute at all.Because grade cant be a negative number. I've used the breakstatement with the if condition but it wont work. Can anyone helpme with how to solve this problem.
Thanks.
Explanation / Answer
please rate - thanks The problems are multiple. first the average doesn't always calculate properly. If youaverage 45 and 46 the program as it stands will give an average 45,when it is truly 45.5. average has to be changed to double orfloat and then sum or students has to be changed also. I'vedone it using casting. the do loop has to be changed to a while loop, and the first inputhas to be outside the loop. This is called priming the loop. also remember if there are no students, don't do the division Since you are using a sentinel to check if you are finished, you nolonger need to ask how many students there are. In thisapplication it's a double check that you don't get more grades thenstudents. but doing so means you must have a check in loop tosee if done code calculating average as double and allowingno students. //Program that calculates average of student grades. #include #include main() { int sum=0, student=0, grade=0, numstudent=0; double average=0; coutnumstudent; coutRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.