Using functions for same output

I was hoping to get an explanation on where to begin on changing the following code to be used with functions. I tried many things but everything seems to not compile.

If any of you can point me to the right direction it would really help. I am only a month and half into my C++ class and have a hard time understanding my professor because I am ESL.

This is the original code that I had no problem writing.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<iostream>
using namespace std;
int main()
{
	int numGrades;
	double grade[100], sum = 0, average, max, min;
 
 	cout << "\nHow many grades do you have? ";
 	cin >> numGrades;
 	cout << "\nList your grades: " << endl;

 	for(int i = 1; i <= numGrades; i++)
 	{
 		cout << "Grade " << i << endl;
 		cin >> grade[i];
 		sum += grade[i];
 	if(i==1)min=max=grade[i]; //1st grade set to min max
 	else if( grade[i] > max)
	{
 		max = grade[i]	;//updates the minmax
 	}
 	else if( grade[i] < min)
 	{
 		min = grade[i] ;
 	}
	
	}
 

 average = sum / numGrades;
 cout<< "\nYour average is = "<< average;
 cout<< "\nYour highest grade is = "<< max
 	 << "\nYour lowest grade is = "<< min;

 	
cout << "\n\n";
return 0;	
}


What my assignment is telling me to do is write out the same thing using functions.
**In my next post**

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
using namespace std;
int grades[100] ;
int n ;

void getgrades() ;
void minimum() ;
void maximum() ;
void average() ;

int main()
{cout << "\nHow many grades do you have? ";
 cin >> n ;
 getgrades() ;
 minimum() ;
 maximum() ;
 average() ;
 
 cout << "\n\n" ;
 return 0;
}


I tried to simply copy and paste the code from the original and separate into each function but it does not work.
well, making stuff global is not the way to go. lets give average a try...
1
2
3
4
5
6
7
8
9
10
11
12
13
double avg (double* grades, int numgrades) //pass data into functions, do not rely on globals to bypass this. 
{
     double sum = 0;
     for (int x = 0; x < numgrades; x++)
     sum += grades[x];
     return (sum/numgrades);
}

…
in main..
...
average = avg(grade, numGrades);
…

Last edited on
Topic archived. No new replies allowed.