This C++ program finds the average of the numbers given by the user. It takes the input from the user on how many numbers have to get the average; Then, it takes the input of those numbers. After receiving the information, it divides the sum of the numbers by the count of the numbers. Next, it assigns the output to a variable and then prints it on the screen.



#include <iostream>
using namespace std;

int main() {
  /* Variable Declaration and Initialization. */
  int n, i;
  float num[100], sum = 0.0, average;

  /* Taking user input */
  cout << "How many numbers do you want to get the average of? ";
  cin >> n;

  /* Validation - The number must be within the range */
  while (n > 100 || n <= 0) {
    cout << "Please enter numbers in the range (1 to 100)." << endl;
    cout << "Enter the number again: ";
    cin >> n;
  }

  /* Taking user input */
  for (i = 0; i < n; ++i) {
    cout << i + 1 << ". Enter a number: ";
    cin >> num[i];
    sum += num[i];
  }

  /* Find avarage */
  average = sum / n;

  /* Prints the output to the screen */
  cout << "Average = " << average;
  return 0;
}

Program Output:

How many numbers do you want to get the average of? 150
Please enter numbers in the range (1 to 100).
Enter the number again: 5
1. Enter a number: 1
2. Enter a number: 2
3. Enter a number: 3
4. Enter a number: 4
5. Enter a number: 5
Average = 3


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram