Calculating the average of all the element in array C++ program example

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Compute the average of array elements in C++ programming

To show: How to find  the average of the array elements in C++ programming

// using two-dimensional array to compute the average of all the elements in array named x

#include <iostream>

using namespace std;

#define m 4

#define n 5

int main(void)

{

int i, j, total = 0;

// 4x5 or [4][5] array variable with initial values

int q[m][n]={{4,5,6,2,12},{10,25,33,22,11},{21,32,43,54,65},{3,2,1,5,6}};

float average;

// outer for loop, read row by row...

for(i=0; i<m; i++)

// inner for loop, for every row, read column by column

for(j=0; j<n; j++)

// get the summation of the array elements.

{

// display the array...

cout<<"q["<<i<<"]["<<j<<"] = "<<q[i][j]<<endl;

total=total + q[i][j];

}

// calculate the average, simple typecast from int to float

average = (float)total/(float) (m*n);

cout<<"\nThis program will calculate the average of the";

cout<<"\n4 x 5 array, which means the sum of the";

cout<<"\narray's element, divide the number of the";

cout<<"\narray's element....";

// display the average

cout<<"Average = "<<total<<"/"<<m*n<<endl;

cout<<"\nThe Average = "<<average<<endl;

return 0;

}

Output example:

q[0][0] = 4

q[0][1] = 5

q[0][2] = 6

q[0][3] = 2

q[0][4] = 12

q[1][0] = 10

q[1][1] = 25

q[1][2] = 33

q[1][3] = 22

q[1][4] = 11

q[2][0] = 21

q[2][1] = 32

q[2][2] = 43

q[2][3] = 54

q[2][4] = 65

q[3][0] = 3

q[3][1] = 2

q[3][2] = 1

q[3][3] = 5

q[3][4] = 6

This program will calculate the average of the

4 x 5 array, which means the sum of the

array's element, divide the number of the

array's element....