summing array values

I have an assignment to do a simple array program that lets the user enter in 10 grades and then the program will average them and output the average. I need to have two functions and main and I am having trouble understanding how to pass my array values from one function to another. I keep getting a "segmentation fault"
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
#include <iostream>
using namespace std;

void getGrades(int grades[])
{
   int numOfGrades = 1;

   for (int i = 1; i <= 10; i++)
   {
      cout << "Grade " << numOfGrades++ << ": ";
      cin >> grades[numOfGrades];
   }
}

void averageGrades(int grades[])
{
   int sumOfGrades;

   for (int i = 1; i <= 10; i++)
      sumOfGrades += grades[i];

   cout << "Average Grade: " << (sumOfGrades / 10) << endl;
}

int main()
{
   int grades[10];
   getGrades(grades);
   averageGrades(grades);

   return 0;
}
Last edited on
closed account (3hM2Nwbp)
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
/* C++ Indices start at 0 */
/* [ code ] Code Here [ /code ] <- Code Tags Are Great */

#include <iostream>
using namespace std;

void getGrades(int grades[])
{
    for (int i = 0; i < 10; i++)
    {
        cout << "Grade " << (i + 1) << ": ";
        cin >> grades[i];
    }
}

void averageGrades(int grades[])
{
    int sumOfGrades;
    for (int i = 0; i < 10; i++)
    {
        sumOfGrades += grades[i];
    }
    cout << "Average Grade: " << (sumOfGrades / 10) << endl;
}

int main()
{
    int grades[10];
    getGrades(grades);
    averageGrades(grades);
    return 0;
}


The segmentation fault was happening because you were writing past the end of your array.

int grades[10] <===> [x] [x] [x] [x] [x] [x] [x] [x] [x] [x]
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [ You were writing out here somewhere. ]
Last edited on
Also, initialize sumOfGrades to 0.
Thanks for the help. Just so I understand what I did wrong, when I initialized int i = 1 in my for loop I skipped the array [0] in grades[10] and when i equaled 10 it was writing outside the array [0] to [9]. So if my array had been int grades[11] it still would have worked when i equaled 10, right?
Yup :) Though not very common in C++ a for each loop is awesome for going through each element of an array and not having to worry about problems like going out of the bounds of an array.
Topic archived. No new replies allowed.