In: Computer Science
C++ Programming-Need getGrades function (I keep getting errors).
Write a function called getGrades that does the following:
Take an array of integers and an integer representing the size of the array as parameters.
Prompt the user to enter up to 20 grades.
Store the grades in the array.
Return the number of grades entered.
Write another function called calcStats that does the following:
Take an array of integers and an integer representing the size of the array as normal parameters.
Use three reference variables to return the lowest, highest, and average grades.
In your main function do the following:
Create an array of 20 elements.
Use the getGrades function to get the grades from the user.
Use the calcStats function to calculate the lowest, highest, and average grades.
Display the results.
Sample output:
Please enter up to 20 grades followed by a -1 when you are
done.
67
87
92
78
82
-1
Lowest grade: 67
Highest grade: 92
Average grade: 81.2
#include<iostream>
using namespace std;
//the below function stores the grades in array upto size or till
-1 is encountered and returns the number of grades entered
int getGrades(int grades[],int size)
{
int gradeCount=0,grade;
cout<<"Please enter up to 20 grades followed by a -1 when you
are done."<<endl;
//read the grade from user
cin>>grade;
//check the grade if it is -1 stop the process otherwise continue
reading next grade
while(1)
{
if(grade==-1 || gradeCount>=size)
break;
grades[gradeCount]=grade; //store the grade in array
++gradeCount;
cin>>grade; //read the next grade from the user
}
return gradeCount;
}
//calculate lowest,highest and average of grades
void calcStats(int grades[],int size,int &lowest,int
&highest,double &average)
{
int i;
double sum=0.0;
lowest=grades[0];
highest=grades[0];
for(i=1;i<size;++i)
{
if(lowest>grades[i])
lowest=grades[i];
if(highest<grades[i])
highest=grades[i];
}
//calculate sum
for(i=0;i<size;++i)
sum+=grades[i];
average=sum/size;
}
int main()
{
//create array of 20 elements
int grades[20];
//call getGrades() to return the total number of grades
int total=getGrades(grades,20);
int lowest,highest;
double average;
//call calcStats() to calculate lowest,highest and average of
grades
calcStats(grades,total,lowest,highest,average);
cout<<"Lowest grade: "<< lowest<<endl;
cout<<"Highest grade: "<< highest<<endl;
cout<<"Average grade: "<< average<<endl;
}
Output