Expectation or expected value of an array | CPP code to calculate expected value of an array ; Function to calculate expectation ; variable prb is for probability of each element which is same for each element ; calculating expectation overall ; returning expectation as sum ; Driver program ; Function for calculating expectation ; Display expectation of given array
#include <bits/stdc++.h> NEW_LINE using namespace std ; float calc_Expectation ( float a [ ] , float n ) { float prb = ( 1 / n ) ; float sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += a [ i ] * prb ; return sum ; } int main ( ) { float expect , n = 6.0 ; float a [ 6 ] = { 1.0 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 } ; expect = calc_Expectation ( a , n ) ; cout << " Expectation ▁ of ▁ array ▁ E ( X ) ▁ is ▁ : ▁ " << expect << " STRNEWLINE " ; return 0 ; }