C++ Program to Calculate Average of Numbers Using Arrays

C++ProgrammingServer Side Programming

Average of numbers is calculated by adding all the numbers and then dividing the sum by count of numbers available.

An example of this is as follows.

The numbers whose average is to be calculated are:
10, 5, 32, 4, 9
Sum of numbers = 60
Average of numbers = 60/5 = 12

A program that calculates average of numbers using arrays is as follows.


 Live Demo

#include <iostream>
using namespace std;
int main() {
   int n, i;
   float sum = 0.0, avg;
   float num[] = {12, 76, 23, 9, 5};
   n = sizeof(num) / sizeof(num[0]);
   for(i = 0; i < n; i++)
   sum += num[i];
   avg = sum / n;
   cout<<"Average of all array elements is "<<avg;
   return 0;


Average of all array elements is 25

In the above program, the numbers whose average is needed are stored in an array num[]. First the size of the array is found. This is done as shown below −

n = sizeof(num) / sizeof(num[0]);

Now a for loop is started from 0 to n-1. This loop adds all the elements of the array. The code snippet demonstrating this is as follows.

for(i = 0; i < n; i++)
sum += num[i];

The average of the numbers is obtained by dividing the sum by n i.e amount of numbers. This is shown below −

avg = sum / n;

Finally the average is displayed. This is given as follows.

cout<<"Average of all array elements is "<<avg;
Published on 27-Sep-2018 16:39:30