- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures

- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces

# C++ Program to Calculate Average of Numbers Using Arrays

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.

## Example

#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; }

## Output

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;

- Related Articles
- Golang Program to Calculate Average Using Arrays
- Swift Program to Calculate Average Using Arrays
- Java program to find the average of given numbers using arrays
- Java program to calculate the average of numbers in Java
- Golang Program to Calculate the Average of Numbers in a Given List
- Calculate average of numbers in a column MySQL query?
- 8086 program to find average of n numbers
- How to calculate GCD of two or more numbers/arrays in JavaScript?
- Write a C program to calculate the average word length of a sentence using while loop
- Splitting array of numbers into two arrays with same average in JavaScript
- Java program to calculate mean of given numbers
- C++ Program to Calculate Sum of Natural Numbers
- MongoDB query to calculate average
- Java program to calculate the product of two numbers
- Java Program to Calculate the Sum of Natural Numbers

Advertisements