Average of 3 numbers

Average of 3 numbers

In this program, we are taking input from the user and calculating the average of entered numbers using “/” operator. The reason why we are using double as data type because a user can enter any data type number such as int, float, long & double, since double can hold the values of all these data types, it is important to declare variables as double data type.
However if you are not taking input from user then you can declare the data type based on the number value, for example if you want to find out the average of three integer numbers then you are declare num1, num2 & num3 as int but you have to use double as the return type of the avr method because the average of 3 int numbers can be a decimal value.

import java.util.Scanner;
public class JavaExample {
 public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        double num1 = scan.nextDouble();
        System.out.print("Enter the second number: ");
        double num2 = scan.nextDouble();
        System.out.print("Enter the third number: ");
        double num3 = scan.nextDouble();
        scan.close();
        System.out.print("The average of entered numbers is:" + avr(num1, num2, num3) );
    }
  public static double avr(double a, double b, double c)
    {
        return (a + b + c) / 3;
    }
}

Output

C:UsersAdarshDesktopjava-programs>java JavaExample

Enter the first number: 12

Enter the second number: 25

Enter the third number: 36

The average of entered numbers is:24.333333333333332

 

Leave Comment

Important Topics

Title
Run and Compile
Hello World Program
User Input
Add Numbers
Sum of Two Numbers
Even Numbers
Odd numbers from 1 to n or 1 to 100
Even or Odd number
Average of 3 numbers
Fibonacci Series using loops
Generate random number
Largest of three Numbers
Decimal to octal conversion
Quotient and Remainder
Simple Interest
Compound Interest