In this tutorial you will learn about the Java Program to Calculate Average of Two Numbers and its application with practical example.
Java Program to Calculate Average of Two Numbers
In this tutorial, we will learn to create a Java program that will Calculate the Average of Two Numbers in Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- Arithmetic operator in Java programming.
What is the average of the numbers?
The average of numbers in mathematics means that all the numbers are added and then the sum of all the numbers is divided by the total number of objects.
It means if there are 4 numbers as follows {2,4,6,8} then the average will be:-
average = 2+4+6+8/4
average = 5.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declaring the variables for the program. 2. Taking the input number from the user to find the average. 3. Calculating the average of the those numbers. 4. Printing the result average of that number to the user. 5. End the program. |
Program to Calculate the average of a Number
In this program, we will take two numbers in input from the user. Then we will add that number and store it in a variable. After that, we will divide the sum of those numbers by 2 to find the average. At last, we will print the average of two numbers.
With the help of this program, we can find the average of two numbers.
Program code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// Find sum and average of two numbers in Java import java.util.*; public class Average { public static void main(String args[]) { //Declaring the required variables for the program int no1, no2, sum; float avg; //Taking the input numbers from the user. Scanner buf = new Scanner(System.in); //Taking the first number System.out.print("Enter first number : "); no1 = buf.nextInt(); //Taking the second number System.out.print("Enter second number : "); no2 = buf.nextInt(); /*Calculate sum and average of two numbers*/ sum = no1 + no2; avg = (float)((no1 + no2) / 2); //Printing the average of two numbers. System.out.print("Sum : " + sum + "\nAverage : " + avg); } } |
Output:-
In the above program, we have first initialized the required variable.
- no1 = it will hold the integer value.
- no2 = it will hold the integer value.
- sum = it will hold the integer value.
- avg = it will hold the float value.
Taking input numbers from the user to for the average of two numbers.
Calculating the average of those numbers.
Printing output average for that given number.