In this example we will calculate the average using array
#include <iostream>
using namespace std;
int main() {
int n, i;
float num[100], sum = 0.0, avg;
cout<<"Enter the numbers of elements: ";
cin >> n ;
while (n > 100 || n < 1) {
cout<<"Error! number should in range of (1 to 100).\n"<<endl;
cout<<"Enter the number again: ";
cin >> n;
}
for (i = 0; i < n; ++i) {
cout<<"Enter number: "<< i + 1 <<endl;
cin >> num[i] ;
sum += num[i];
}
avg = sum / n;
cout<<"Average = " <<avg <<endl;
return 0;
}
Explanation:
- User Input:
- The user is asked to input the number of elements to average. Let’s say the user enters
3
. - The user then inputs the 3 numbers, say
5.5
,6.0
, and8.0
.
- The user is asked to input the number of elements to average. Let’s say the user enters
- Process:
- The code will check if the input number of elements (
n
) is between1
and100
. If not, it will ask the user to input the number again. - For each number, the code will prompt the user to enter it and then calculate the sum.
- Finally, the average is calculated by dividing the sum by
n
.
- The code will check if the input number of elements (
Output:
Enter the numbers of elements: 3
Enter number: 1
5.5
Enter number: 2
6.0
Enter number: 3
8.0
Average = 6.5
- The user inputs
3
for the number of elements. - The user inputs
5.5
,6.0
, and8.0
as the numbers. - The sum of the numbers is:
5.5 + 6.0 + 8.0 = 19.5
. - The average is:
19.5 / 3 = 6.5
. - The program prints
Average = 6.5
.