Hi I'm new to c++ programming. This is my first ever program, it calculates the average of numbers that the user input. The user can input up until 10 numbers. I get a segmentation fault for some reason. Any ideas?

#include<iostream>
using namespace std;


int main()

{

  int numbers[10]; // array could have up until 10 numbers.
  int sum = 0;     // intial sum.
  int count = 0;   // initial count.
  int average;     // Average.
  int i;       // input


  while (cin >> numbers[i])
    {
      i++;
      
      sum = sum + numbers[i];
      count = count +1;
    }

  average = sum/count; 
  cout <<average<< endl;
}

Edited 6 Years Ago by Nick Evan: Added code-tags

I get a segmentation fault for some reason. Any ideas?

Yes, you should make sure that you don't override the array boundaries.
Therefore you should rather change your code to something like this:

#include <iostream>
using namespace std;

int main()
{
  const int MAX_ARRAY_SIZE = 10;
  int numbers[MAX_ARRAY_SIZE];
      // array can hold up to MAX_ARRAY_SIZE elements
  int sum = 0;    // initial sum
  int count = 0;  // initial count
  int average;    // average
  int i;  // input
  
  for (int i = 0; i < MAX_ARRAY_SIZE && (cin >> numbers[i]); i++)
  {
    sum = sum + numbers[i];
    count = count + 1;
  }
  
  average = sum / count;
  cout << average << endl;
}

As you can see in the above code, a protection is added to make sure that we won't write data to an array index which is higher than MAX_ARRAY_SIZE.
And that's not all, bear in mind that the average in your code is computed by an integer division, that means: precision isn't preserved, an example of this:

// Assume integer divisions
1/5 != 0.2 but 0
5/2 != 2.5 but 2

In fact, an array isn't even needed if you want to calculate the average of a list of numbers entered by the user, here's an example which takes a list of integers and computes the average from it:

#include <iostream>
using namespace std;

int main()
{
  int sum, count, tmp;
  sum = count = tmp = 0;
  
  while ( cin >> tmp ) {
    sum += tmp;
    count++;
  }
  
  cout << "Average: " << (double) sum / count << endl;
}

Edited 6 Years Ago by mvmalderen: n/a

Thanks alot for your help. For some reason, I still would get the error if I use a while loop. But I guess, I'll just use a for loop. The thing is I have to use an array, because I want to store the numbers so I can use them later on.

Edited 6 Years Ago by higuain14: n/a

For some reason, I still would get the error if I use a while loop. But I guess, I'll just use a for loop.

It can also be done using a while loop, as long as you write code which will prevent the array's boundaries to be overrun.

This question has already been answered. Start a new discussion instead.