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  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 = 4

q = 5

q = 6

q = 2

q = 12

q = 10

q = 25

q = 33

q = 22

q = 11

q = 21

q = 32

q = 43

q = 54

q = 65

q = 3

q = 2

q = 1

q = 5

q = 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....