In this tutorial you will learn about the C++ Program to Calculate Average of Numbers Using Arrays and its application with practical example.
C++ Program to Calculate Average of Numbers Using Arrays
In this tutorial, we will learn to create a C++ program that will average the elements of Array using C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
- For loop in C++ Programming.
Average of numbers:-
The average number means the sum of all the terms, divided by the number of terms. The resultant will be the average of numbers.
1 2 3 4 5 |
<strong>For example :-</strong> Array containing the elements { 2 , 3 , 4 , 5 , 6 } Total of the elements = 20. Number of terms = 5. Average of numbers = 4. |
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables and arrays. 2. Taking input in Array. 3. Adding the elements of the arrays. 4. Finding the average of the elements of the array. 5. Printing the average of the array. 6. End Program. |
Program to Calculate Average of Numbers Using Arrays:-
As we all know array is a collection of similar data type elements. we can perform many different operations on arrays in c++ programming. In today’s program, we will take an array as an input and then we will find the average of all of its elements.
Program:-
To find the Average value element from the array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include <iostream> using namespace std; int main() { //declring the variables for the program. int n, i; float num[100], sum=0.0, average; //taking the size of array in the program. cout << "Enter the numbers of data: "; cin >> n; //taking the elements of the array. while (n > 100 || n <= 0) { cout << "Error! number should in range of (1 to 100)." << endl; cout << "Enter the number again: "; cin >> n; } for(i = 0; i < n; ++i) { cout << i + 1 << ". Enter number: "; cin >> num[i]; sum += num[i]; } //printing the average of the program average = sum / n; cout << "Average = " << average; return 0; } |
Output:-
In the above program, we have first initialized the required variable
- num = it will hold the elements in an array.
- n = it will hold the number of elements in an array.
- i = it will hold the integer value to control the array.
- sum= it will hold the float value for the sum of the array.
- avg= it will hold the float value for the average of the array.
Taking input from the user in an array number of elements in the array.
Taking input from the user in array elements in the array.
Sum of the array.
Calculating the Average of Array printing the output number.