C++ Program to Calculate the Average of Two Numbers

Average of two numbers

C++ program to calculate the average of two numbers has been shown here. Average of two numbers is described by the sum of those numbers divided by 2. Suppose $a$ and $b$ are two numbers, then the average is calculated as $\frac{a+b}{2}$.

For example, if the two numbers are 5 and 6, the average is (5 + 6)/2 = 5.5.






1. Algorithm to Calculate the Average of Two Numbers


1. Take two numbers a and b as inputs

2. Compute x = (a + b)/2

3. Declare x as the average and exit program




2. Pseudocode to Calculate the Average of Two Numbers


Input: Two numbers $a$ and $b$

Output: Average of $a$ and $b$

1. Procedure average($a$, $b$):

2. $x \leftarrow \frac{a+b}{2}$:

3. Return $x$

4. End Procedure





3. Time Complexity to Calculate the Average of Two Numbers


Time Complexity: O(1)




4. C++ Program to Calculate the Average of Two Numbers

Code has been copied
/*****************************
    alphabetacoder.com
C++ Program to calculate the 
average of two numbers
******************************/
#include <iostream>

using namespace std;

int main() {
    // declare variables
    float a, b, x;

    //take input of the numbers
    cout << "Enter the first number = ";
    cin >> a;
    cout << "Enter the second number = ";
    cin >> b;

    // calculate average
    x = (a + b) / 2;

    // display the result
    cout << "Average of " << a << " and " << b << " is " << x << endl;

    return 0;
}

Output


Enter the first number = 10.5

Enter the second number = 5.75

Average of 10.5 and 5.75 is 8.125