Array problems

I'm making a program that ask the user for 10 grades so that the program can average it out but I'm only getting 1 as the average. Plus if anyone can explain passing arrays through other functions that would be nice too.
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
#include <iostream>
using namespace std;

int getGrades()
{
  int grade[10];
  for(int i = 1; i < 11; i++)
    {
      cout << "Grade " << i << ": ";
      cin >> grade[i];
    }
  return grade[10];

}

int averageGrades(int grade[10])
{
  int sum, quotion;
  for(int j = 0;j < 10; j++)
    {
      sum = grade[9] + grade[8] + grade[7] + grade[6] + grade [5] + grade[4] + \
grade[3] + grade[2] + grade[1] + grade[0];
    }
  quotion = sum / 10;
  return quotion;
}

int main(int quotion)
{
  getGrades();
  cout << "Average Grade: " << quotion << "%";
   return 0;
}
1
2
3
4
5
for(int j = 0;j < 10; j++)
    {
      sum = grade[9] + grade[8] + grade[7] + grade[6] + grade [5] + grade[4] + \
grade[3] + grade[2] + grade[1] + grade[0];
    }

What is the meaning of that?

And do you really need the result to be returned to the main ?
A little bit modified, but still same idea, have fun :)
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
#include <iostream>
using namespace std;
double averageGrades(double grade[], int size);
double getGrades()
{
  double grade[9],res;
  for(int i = 0; i < 10; i++)
    {
      cout << "Grade " << i+1 << ": ";
      cin >> grade[i];
    }
  res=averageGrades (grade, 10);
  return res;
}

double averageGrades(double grade[], int i)
{
  double sum =0;
  double quotion;
  for(int j=0;j < i; j++)
          sum +=grade[j]; // If there is only onу function in the for loop, no brackets are needed 
 
  return sum / 10;;
}

int main()
{
double quotion;
  quotion = getGrades();
  cout << "Average Grade: " << quotion << "%";
 system("pause");
   return 0;
}
I love you bro thanks totally helped. What I want to understand though is that why don't you put the [] here res=averageGrades (grade, 10); I still don't understand passing arrays through functions very much and my teacher wants us to get in the habit of using multiple functions.
const int NUM_GRADES = 10;

is preferred to magic numbers, notice that magic numbers cause a problem in this example because the array is only 9 members long while the FOR loop iterates 10 times. A const int prevents this.

edit: just to clarify, replace all of the cases of 10 or 9 in the code, which are meant to reference the number of grades to average, with NUM_GRADES.

for example:
for(int i = 0; i < NUM_GRADES; i++) // do something;
Last edited on
Topic archived. No new replies allowed.