Java Program to find Average of Two Numbers

In this article, you will learn how to find the average of two given numbers and write its program in java language. The average of the two numbers is the sum of two numbers divided by 2. Let’s assume a and b are two numbers. Now see the calculation below:

The average of two numbers = ( The sum of given two numbers ) / 2

Average = ( a + b ) / 2

For example:
a=5; b=8
Average => a+b/2 => 5+8/2 => 13/2 => 6.5

Below is the java program to find the average of two given numbers,

package com.javacodepoint.basics;

import java.util.Scanner;

public class AverageOfTwoNumbers {

	// main method
	public static void main(String[] args) {

		// declaring num1 & num2 variables to take two numbers, sum variable to
		// calculate sum, and average to calculate average
		float num1, num2, sum, average;

		// Scanner object for reading two numbers from user input
		Scanner sc = new Scanner(System.in);

		// reading first number
		System.out.println("Enter the first number: ");
		num1 = sc.nextFloat();

		// reading second number
		System.out.println("Enter the second number: ");
		num2 = sc.nextFloat();

		// calculating sum of given two numbers
		sum = num1 + num2;

		// calculating the average of given two numbers
		average = sum / 2;

		// Printing the calculated average
		System.out.println("The average of the given two Numbers= " + average);

	}

}

OUTPUT:

Enter the first number:
2
Enter the second number:
8
The average of the given two Numbers= 5.0

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

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