on Leave a Comment

Java Program to Find the Largest of Three Numbers

In this article we'll see how to find largest of three numbers in java. 

We will see, Java program to find the largest of three numbers using
(1) If-Else..If Statement
(2) Nested If..Else Statement

Example 1: Java Program to Find the Largest of Three Numbers Using If-Else..If Statement

import java.util.Scanner;
public class LargestOf3{

    public static void main(String[] args) {

        int a, b, c;
        Scanner read = new Scanner(System.in);
        System.out.print("Enter Three Numbers: ");
        a = read.nextInt();
        b = read.nextInt();
        c = read.nextInt();
        
        if( a >= b && a >= c)
            System.out.println(a + " is the largest number.");

        else if (b >= a && b >= c)
            System.out.println(b + " is the largest number.");

        else
            System.out.println(c + " is the largest number.");
    }
}

Output:

Enter Three Numbers: 10 20 30
30 is the largest number.

Example 2: Java Program to Find the Largest of Three Numbers Using Nested If..Else Statement

import java.util.Scanner;
public class LargestOf3{

    public static void main(String[] args) {

        int a, b, c;
        Scanner read = new Scanner(System.in);
        System.out.print("Enter Three Numbers: ");
        a = read.nextInt();
        b = read.nextInt();
        c = read.nextInt();

        if(a >= b) {
            if(a >= c)
                System.out.println(a + " is the largest number.");
            else
                System.out.println(c + " is the largest number.");
        }
        else {
            if(b >= c)
                System.out.println(b + " is the largest number.");
            else
                System.out.println(c + " is the largest number.");
        }
    }
}

Output:

Enter Three Numbers: -10 0 10
10 is the largest number.




0 comments:

Post a Comment