Open In App

Program to find the average of two numbers

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given two Integers A and B, your task is to find the average of two numbers where the average is given by the formula:
average(A, B) = (A+B)/2

Examples:

Input: A=5, B=3
Output: 4
Explanation: Average(A,B) = (A+B)/2 = 8/2 =4

Input: A=10, B=5
Output: 7.5
Explanation: Average(10, 5) = (10 + 5)/2 = 15/2 = 7.5

Approach: To solve the problem, follow the below idea:

We can find the average of two number by summing the number using the ‘+’ operator and then divide the sum by 2 to get the final answer.

Step-by-step algorithm:

  • Read the integers A and B from the user.
  • Calculate the sum: C = A + B
  • Calculate the average: average = sum / 2
  • Display the result.

Below is the implementation of the algorithm:

C++
#include <iostream>
using namespace std;

int main()
{
    int A = 10;
    int B = 5;

    // First find the sum of two numbers
    int sum = (A + B);

    // Then divide the sum by 2 to get the average
    double average = sum / 2.0;
    cout << "Average of " << A << " and " << B << " = "
        << average << endl;
}
Java
public class Main {
    // Function to calculate sum of two numbers
    static int sum(int A, int B) {
        int result = A + B;
        return result;
    }

    // Function to calculate average of two numbers
    static double average(int A, int B) {
        double result = sum(A, B) / 2.0;
        return result;
    }

    public static void main(String[] args) {
        int A, B;
        A = 10;
        B = 5;
        double C = average(A, B);
        System.out.println(&quot;Average of &quot; + A + &quot; and &quot; + B + &quot; = &quot; + C);
    }
}
C#
using System;

class Program
{
    static void Main()
    {
        // Declare and initialize variables
        int A = 10;
        int B = 5;

        // First, find the sum of two numbers
        int sum = A + B;

        // Then, divide the sum by 2 to get the average
        double average = sum / 2.0;

        // Print the result
        Console.WriteLine($"Average of {A} and {B} = {average}");
    }
}
Javascript
// Declare and initialize variables
let A = 10;
let B = 5;

// First, find the sum of two numbers
let sum = A + B;

// Then, divide the sum by 2 to get the average
let average = sum / 2.0;

// Print the result
console.log(`Average of ${A} and ${B} = ${average}`);
Python3
def sum_numbers(A, B):
    result = A + B
    return result

def average(A, B):
    result = sum_numbers(A, B) / 2.0
    return result

# Main program
if __name__ == &quot;__main__&quot;:
    A = 10
    B = 5
    C = average(A, B)
    print(f&quot;Average of {A} and {B} = {C}&quot;)

Output
Average of 10 and 5 = 7.5

Time Complexity: O(1)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads