In this post, you will learn how to Calculate Average Using Arrays in C++ programming language.
This lesson will teach you how to Calculate Average Using Arrays, using mathematical operators, logical operator and the for loop statement using the C++ Language. Let’s look at the below source code.
How to Calculate Average Using Arrays?
RUN CODE SNIPPETSource Code
#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
The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code.
Now we can look into the working and layout of the code’s function.
- Declare the variables n, i as integers and sum, avg, num as float values. The float datatype is used when decimal values are used or displayed in the process.
- Assign the float variable as follows :
float sum = 0.0; float num[] = {12, 76, 23, 9, 5};The variable sum is assigned to 0.0 and the variable num is assigned with the array of numbers for which the average is to be calculated. - In this code we insert the input values in the code, rather than getting them from the user. The [ ] is used to specify that the variable is to hold an array value.
- Calculate the value of n by using the mathematical function
n = sizeof(num) / sizeof(num[0]) - Declare a for loop with the condition
(i = 0; i < n; i++), followed by the a logical function with the AND addition operator to add the values of the array. - Next find the average of the values of the array using the mathematical function
avg = sum / n. - Use the output function cout to display the output statement and the Average of the array of numbers.