Loops and Arrays

Hello,

I'm a writing a basic program that calculates average, variance, and standard deviation for a set of entered numbers using arrays and loops. I've written this program on an online platform (Vocareum).

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
#include <iostream>
#include <cmath>

using namespace std;

int main ()
{
    int n, i(0);
    double sum(0), sumvar(0), array[i];
    
    cout << "How many numbers do you wish to enter? ";
    cin >> n;
    
    cout << "Enter " << n << " numbers: ";
    
    for (i == 0; i < n; i++)
    {
        cin >> array[i];
        sum += array[i];
    }
    
    cout << "The average is " << sum/n << endl;
    double avg = sum/n;
    
    for (i == 0; i < n; i++)
    {
        sumvar += pow(( array[i] - avg ), 2);
    }
    
    double variance = sumvar/n;
    cout << "The variance is " << variance << endl;
    
    cout << "The standard deviation is " << sqrt(variance) << endl;
    
    return 0;
}


The program seems to run fine if the entered numbers (n) is less than 5.

If 5 numbers are entered, this is the output:


How many numbers do you wish to enter? 5
Enter 5 numbers: 1
2
3
4
5
../resource/scripts/run.sh: line 1: 26870 Segmentation fault (core dumped)


If the user tries to enter more than 5 numbers, the program crashes like above after the fifth number is entered.

From my understanding, array elements start at 0 rather than 1, so it would make sense that the index i should be initialized to 0 and finish at n-1 to store all numbers entered.

Any advice on the matter would be greatly appreciated.
How many elements are in the array?
1
2
int i(0);
double array[i];

That is the maximum number of values that you can store in it.

You need a larger array:
1
2
3
4
5
6
constexpr int N {100};
double array[N] {};
int n {0};
std::cin >> n;
if ( N < n ) n = N;
// now you can put n values into array 
Topic archived. No new replies allowed.