Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Calculate average using array

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:

  1. 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, and 8.0.
  2. Process:
    • The code will check if the input number of elements (n) is between 1 and 100. 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.

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

  1. The user inputs 3 for the number of elements.
  2. The user inputs 5.5, 6.0, and 8.0 as the numbers.
  3. The sum of the numbers is: 5.5 + 6.0 + 8.0 = 19.5.
  4. The average is: 19.5 / 3 = 6.5.
  5. The program prints Average = 6.5.

    Leave a Reply

    Your email address will not be published.

    Need Help?