C++ Program For Average of 5 Numbers

Write a C++ Program For Average of 5 Numbers. Take 5 numbers from the end-user and calculate the average value. We can also solve this problem through arrays.

The user can enter integer or floating point numbers therefore to store those five numbers we will use float or double type variables. 

The average of five numbers can be calculated as,
average = (sum of five numbers) / 5

#include<iostream>
using namespace std;
// main function
int main()
{
  // variables to store input values
  double n1, n2, n3, n4, n5; 
  double avg; // to store result

  // take input values
  cout << "Enter five numbers: ";
  cin >> n1 >> n2 >> n3 >> n4 >> n5;
  
  // calculate average value
  avg = (n1 + n2 + n3 + n4 + n5)/5;
  
  // display result
  cout << "Average = " << avg << endl;

  return 0;
}

Output:-

Enter five numbers: 10 20 30 40 50
Average = 30

Enter five numbers: 15.5 25.5 10.2 30.5 63.9
Average = 29.12

In this program, we declared five floating point numbers to store the input values. Then, we took input from the end-user. Using the average formula we have calculated the average value, and displayed it to the screen.

Average of 5 Numbers in C++ Using Array

Array is used to store the multiple values of the same type using one variable. In the previous example, to store 5 numbers we need five variables but using the array we can do the same using only one array variable. To access the array elements loop can be used.

C++ Program For Average of 5 Numbers using Array

#include<iostream>
using namespace std;
// main function
int main()
{
  // array variable to store 5 numbers
  double arr[5]; 
  double sum; // to store sum 
  double avg; // to store result

  // take input values
  cout << "Enter five numbers: ";
  for (int i = 0; i < 5; ++i)
  {
    cin >> arr[i];
  }
  
  // calculate sum value
  sum = 0;
  for (int i = 0; i < 5; ++i)
  {
    sum += arr[i];
  }

  // calculate average value
  avg = sum/5;
  
  // display result
  cout << "Sum = " << sum << endl;
  cout << "Average = " << avg << endl;

  return 0;
}

Output:-

Enter five numbers: 10 20 30 40 50
Sum = 150
Average = 30

Enter five numbers: 12.5 15.9 28.6 23.7 14.9
Sum = 95.6
Average = 19.12

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Learn more C++ Programming Examples

Leave a Comment

Your email address will not be published. Required fields are marked *