print_avg only reading in first element

So I'm trying to read in an array of years and print how many of those years are over the average. I know the problem lays in my print_avg function but I can't see why it won't work. Any help?

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
39
40
41
42
43
44
45
46
47
48
49
50
  #include <iostream>
  using namespace std;
  
  const int SPACE = 3001;
  const int SENTINEL = -1;
  
  double average(int years[], int count);
  int print_avg(int years[], double avg);
  
  int main()
  {
          int over_avg = 0;
          int years[SPACE];
          int count = 0;
          int year;
          double avg;
          do {
                  if (count > SPACE - 1) {
                          cout << "too much data!" << endl;
                          return 1;
                  }
                  cin >> year;
                  years[count++] = year;
          } while (year != SENTINEL);
  
          avg = average(years, count);
          over_avg = print_avg(years, avg);
  
          cout << over_avg << endl;
          return 0;
  }
  
  double average(int years[], int count)
  {
          double sum = 0;
          for (int i=0; i < count - 1; i++) {
                  sum += years[i];
          }
          return sum/(count-1);
  }
  
  int print_avg(int years[], double avg)
  {
          int count = 0;
          int over_avg = 0;
          if (years[count++] > avg) {
                  over_avg++;
          }
          return over_avg;
 }
Last edited on
Line 46-47: You have no loop iterating through the array. You're checking the first entry and that's all.

Line 22-23: If the user enters -1, you're adding the -1 to the array and incrementing count. You do allow for this at lines 36 and 39, just a little unorthodox. One doesn't normally put a sentinel value in array and count it.
You're only checking the first element of your array so unless the first element is larger than the average the function should return 0.

You should also pass the number of entered elements into this function, if you decide to use a loop to check each element.

Lastly you probably should print the array after you're finished entering them, just so you can verify that all the correct data was saved.

Topic archived. No new replies allowed.