Average of Two Numbers in C++

Program Description:- Find the average of two numbers in C++ language. Take two numbers from the end-user, find the sum then find the average of those numbers.

Assume we have two numbers:- x, and y. Then,
Sum of two numbers = x + y
Average = (Sum of two numbers) / 2

To take input from the user cin is used, and to display the output message cout is used. Let us develop the program to find the average of Two Numbers in C++.

C++ Program to Find the Average of Two Numbers

The input value can be integer number or floating point number therefore we will take the float/double data type to store the input and result values.

#include<iostream>
using namespace std;
// main function
int main()
{
   // declare variables
   double x, y; // to store input
   double sum; // to store sum
   double avg; // to store average

   // take input values
   cout << "Enter two numbers: ";
   cin >> x >> y;
  
   // calculate sum value
   sum = x + y;

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

   return 0;
}

Output:-

Enter two numbers: 10 20
Sum = 30
Average = 15

Enter two numbers: 12.9 23.89
Sum = 36.79
Average = 18.395

Enter two numbers: -15.3 56.5
Sum = 41.2
Average = 20.6

In this program, first of all, we declared all the variables required in this program. All the variables are of double data type so that they can store both integer and floating-point numbers, and they can store big numbers. To find the average value, first we must find the sum of those numbers. Then the average is calculated as average = sum/2. Finally, the result values i.e. sum and average values are displayed on the screen.

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

Leave a Comment

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