Is there an alternative way to calculate Standard Deviation using pointers?

Hello,

I have written the following code to dynamically allocate some elements to a dynamic array, then to compute the standard deviation from the elements. I was just wondering, is there a better way to do this using pointers? I just feel like I am missing something here.

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <cmath>

using namespace std; 

double StandardDeviation(double[], double, int);
double x_mean(double[], int);
void DataEntry(int, double []);
void DisplayData(double [], int);

//function to calc mean
double x_mean(double DataArray[], int x)
{
    double sum = 0;
    double mean = 0;
    for (int i = 0; i < x; i++)
    {
        sum = sum + DataArray[i];
    }
    mean = sum / x;
    cout << "The mean is " << mean << endl;
    return mean;
}

//Function to calculate the sum of x - x_mean
double StandardDeviation(double DataArray[], double x_mean, int x)
{
    double sum = 0.0;
    double standardDeviation = 0.0;

    for (int i = 0; i < x; ++i)
    {
        sum += DataArray[i];
    }

    for (int i = 0; i < x; ++i)
        standardDeviation += pow(DataArray[i] - x_mean, 2);

    return sqrt(standardDeviation / x);
}
//Function for data entry
void DataEntry(int x, double DataArray[])
{
    for (int i = 0; i < x; i++)
    {
        cout << "What number would you like to enter? " << endl;
        cin >> DataArray[i];
    }
    cout << "Data Entry Complete" << endl;
}

void DisplayData(double DataArray[], int j)
{
    for (int i = 0; i < j; i++)
    {
        cout << DataArray[i] << endl;
    }
}

int main()
 {
    int n = 0;

    cout << "How many numbers in your data set?" << endl;
    cin >> n;
    cout << "The total of numbers in your data set is " << n << endl;
    double* x = new double[n];
    
    DataEntry(n, x);
    DisplayData(x, n);

    double xmean = x_mean(x, n);
    cout << "Standard Deviation = "<< StandardDeviation(x,xmean, n) << endl;

    delete[] x;

    return 0;
}
If you can use std:vectors instead of dynamic arrays. Less overhead, the vector manages its own memory, knows its size automatically and passing a vector into an array can be done using a reference so no copy is made.
https://tutorialspoint.dev/language/cpp/passing-vector-function-cpp
Topic archived. No new replies allowed.