Home > DeveloperSection > Blogs > How to find the largest and smallest number among three input numbers using “if else if”

How to find the largest and smallest number among three input numbers using “if else if”


Java Java 
Ratings:
0 Comment(s)
 426  View(s)
Rate this:

How to find the largest and smallest number among three input numbers using “if else if

 

Finding the largest and the smallest number among three input numbers can be done with the help of “if, else if” statements. We could simply have use just if statements to find the output but that’s not correct. The difference is that if the first if is true, all of the other else ifs won't be executed, even if they do evaluate to true. If they were individual ifs, however, all of the ifs will be executed if they evaluate to true.

 

package program1;

import java.io.*;

public class Program1 {

    public static void main(String[] args)throws IOException {

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        int a,b,c;

               

                    System.out.println("Enter first number");

                    a=Integer.parseInt(br.readLine());

                    System.out.println("Enter second number");

                    b=Integer.parseInt(br.readLine());

                    System.out.println("Enter third number");

                    c=Integer.parseInt(br.readLine());

                   

                    if(a>=b && a>=c)

                        System.out.println("Largest number is "+ a);

                    else if(b>=a && b>=c)

                        System.out.println("Largest number is "+ b);

                    else if(c>=a && c>=b)

                        System.out.println("Largest number is "+ c);

                   

                    if(a<=b && a<=c)

                        System.out.println("Smallest number is "+ a);

                    else if(b<=a && b<=c)

                        System.out.println("Smallest number is "+ b);

                    else if(c<=a && c<=b)

                        System.out.println("Smallest number is "+ c);        

                   

               

    }

}

 

It will generate the following output:

Enter first number

34

Enter second number

23

Enter third number

78

Largest number is 78

Smallest number is 23


Don't want to miss updates? Please click the below button!

Follow MindStick