Example: Calculate Average of Numbers Using Arrays
#include <iostream>
using namespace std;
int main()
{
int n, i;
float num[100], sum=0.0, average;
cout << "Enter the numbers of data: ";
cin >> n;
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];
}
average = sum / n;
cout << "Average = " << average;
return 0;
}
Output
Enter the numbers of data: 6 1. Enter number: 45.3 2. Enter number: 67.5 3. Enter number: -45.6 4. Enter number: 20.34 5. Enter number: 33 6. Enter number: 45.6 Average = 27.69
This program calculates the average of all the numbers entered by the user.
The numbers are stored in the float
array num, which can store up to 100 floating-point numbers.
We first ask the user to specify how many numbers we will be calculating. This is stored in the variable n.
If the user enters a value of n above 100 or below 1, a while
loop is executed which asks the user to enter a value of n until it is between 1 and 100.
while (n > 100 || n <= 0)
{
cout << "Error! number should in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
Then, we use a for
loop to input the numbers from the user and store them in the num array.
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
Every time a number is entered by the user, its value is added to the sum variable.
By the end of the loop, the total sum of all the numbers is stored in sum.
After storing all the numbers, average is calculated and displayed.
average = sum / n;
Also Read: