Solution Review: Calculate Mean and Standard Deviation from Array
Let's go over the solution review of the challenge given in the previous lesson.
Solution
Press the RUN button and see the output!
Press + to interact
C++
#include <iostream>#include <cmath>using namespace std;int main() {int size = 10;//Declare dynamic arrayint *Array = new int[size];//Initialize dynamic arrayfor(int i = 0 ; i < size; i++){Array[i] = rand() % 100;}//Prints dynamic arraycout << "Elements of array: ";for(int i = 0 ; i < size; i++){cout << Array[i] << " ";}cout << endl;//Calculate mean and printfloat sum = 0;for(int i = 0 ; i < size; i++){sum += Array[i];}float mean = sum/size ;cout << "Mean: " << mean << endl;//Calculate standard deviation and printfloat stdDev = 0;for(int i = 0 ; i < size; i++){stdDev += pow(Array[i] - mean, 2);}stdDev = sqrt(stdDev / size);cout << "Standard Deviation: " << stdDev << endl;// Deletes a memory allocated to dynamic arraydelete[] Array;}
Explanation
- First, we allocated the dynamic