Saturday, September 23, 2023

How to Find Largest of Three Integers in Java - Algorithm, Logic Example

One of the classical programs to build programming logic is, write a program to find the largest of three numbers. I am sure many of you have already done this exercise in a variety of languages including C, C++, C#, JavaScript, Perl, Ruby, PHP, etc. This time we will do it in Java. We will first learn the logic by understanding the flowchart of the largest of three numbers and then we will implement a solution using the ternary operator in Java. I love this program for its sheer simplicity and how it can help beginners to build logic. As always, you are not allowed to use any library function which can solve this problem directly, your main task is to build logic using primitive language tools e.g. operators.

In Java, this problem is also used to teach how a ternary operator works, as one of the popular versions of this requires you to find the largest of three numbers using a ternary operator.

This problem is in a similar category as to how to determine if the number is prime. This Java program finds the largest of three numbers and then prints it. If the entered numbers are unequal then one version of this program returns Integer.MIN_VALUE, while others return the number itself.

By the way, the method used here is not general and doesn't scale well for many numbers. For example, If you want to find out the largest of a list of numbers say 10 integers then using the above approach is not easy, instead you can use array data structure, and keep track of the largest number while comparing with other numbers.

We will also see how we can use the ternary operator in Java to find the biggest of three integers. I have made both method static because they are actually utility method and only operates on their arguments, and I can call them from the main method directly, without creating an object of this class.

Btw, it's essentials for every programmer to know about basic data structures like an array, linked list, binary tree, hash table, and others. It helps you to write better code and also crack interviews, if you want to brush up your algorithms skills then you can also join a comprehensive Data Structure and Algorithms courses to fill the gaps in your understanding.



Logic to find Greatest of Three Integers in Java

Algorithm or logic is independent of programming language. More or less they are same in every language. For example, if you build logic without using library method e.g. only based upon standard operators and data structures e.g. array, you can use them in different language.



For example, first logic can be used in JavaScript, C, C++ or C#. Second logic uses a special operator, known as a ternary operator, as it has three arguments, that's why it can only be applied to languages which support ternary operator e.g. Java. 

Logic to find the biggest of three number is as follows :
  1. Check if the first number is greater than the second and third, if Yes, then first number is largest.
  2. Check if the second number is greater than second and third, if Yes, the second number is the largest.
  3. Otherwise, the third number is the largest.


This is the most simple logic of finding maximum of three numbers, it can't be simpler than this. By the way, there is some opportunity to improve my logic of finding biggest of three, as you may notice, I am comparing the same numbers more than one time. I leave that as exercise for you, but will give you some hint in the flowchart, which we will see in next section.


Largest of Three Numbers FlowChart

This is the flowchart of finding the largest of three numbers in Java, it first reads three numbers A, B, and C from the console, using utilities like Scanner. Then it first compares A against B, if A > B then it goes to compare A and C. If A > C, the A is the largest number, else C is the maximum number. 

On the other hand, if A < B in the first comparison then the second comparison happens between B and C if B > C then B is largest otherwise C is the largest number. 

This logic is shown below flowchart, I am sure it's much easier to understand a flowchart than its description :)

How to find largest of three numbers in Java, flowchart, ternary operator



The complexity of Our Solution

If you look at the flowchart, you will find that we at least need to do two comparisons to find the maximum of three numbers. To understand this, you can see how many diamond boxes we are using in each path, there are only two. 

So to find the maximum of three numbers, we have done 2 comparisons, which means to find the maximum of n numbers, we need to do the n-1 comparison. That's why the time complexity of this solution is O(n).


Java Program to Find Largest of Three Numbers

Here is our complete Java solution to this problem. As I said before, we have two solutions, one which finds the largest of three numbers using the ternary operator and the other which uses if-else-if loop. 

First solution is very simple as it compares numbers more than required, in the worst case it does 8 comparisons. 

The second solution uses the logic from the flowchart and only does two comparisons to find the largest of three. This example is also user-driven, we read input from user, and then feed them into our method to find the biggest of three numbers. 

You are free to improve the logic, but don't forget to explain why it's better, this is where you score.

import java.util.Scanner;
 
/**
* Java program to find largest of three Integer numbers. 
* You can not use any library method to 
* solve this problem. You need to build logic by yourself. 
* Input : 3, 5, 7
* Output : 7
*
* @author Javin Paul
*/

public class LargestOfThree{

    public static void main(String args[]) {

        Scanner cmd = new Scanner(System.in);
        System.out.println("Please enter three different numbers 
                      to find largest of them");
        int first = cmd.nextInt();
        int second = cmd.nextInt();
        int third = cmd.nextInt();

        int largest = largestOfThree(first, second, third);
        System.out.printf("Largest of three numbers, 
                    between %d, %d and %d is %d %n",
                first, second, third, largest);

        int greatest = greatestOfThreeUsingTernaryOperator(first, 
                              second, third);
        System.out.printf("Greatest of three numbers in Java 
                          using ternary operator is %d %n", greatest);

        //close the scanner to prevent resource leak
        cmd.close();

    }

    /**
     * Find largest of three numbers in Java. All three numbers must be
     * distinct.
     *
     * @param first
     * @param second
     * @param third
     * @return largest of three numbers, or Integer.MIN_VALUE 
     * if numbers are not
     * distinct.
     */
    public static int largestOfThree(int first, int second, int third) {
        if (first > second && first > third) {
            return first;
        } else if (second > first && second > third) {
            return second;
        } else if (third > first && third > second) {
            return third;
        }
        return Integer.MIN_VALUE;
    }

    /**
     * function to find largest of three numbers in Java using 
     * ternary operator
     * @param one
     * @param two
     * @param three
     * @return biggest of three numbers
     */
    public static int greatestOfThreeUsingTernaryOperator(int one,
                  int two, int three) {
        return (one > two) ? (one> three ? one : three) 
                           : (two > three ? two : three);
    }

}
 
Output:
Please enter three different numbers to find largest of them
11
21
31
Largest of three numbers, between 11, 21 and 31 is 31 
Greatest of three numbers in Java using ternary operator is 31 
 
Please enter three different numbers to find largest of them
4
5
4
Largest of three numbers, between 4, 5 and 4 is 5 
Greatest of three numbers in Java using ternary operator is 5
 
Please enter three different numbers to find largest of them
23
23
23
Largest of three numbers, between 23, 23 and 23 is -2147483648 
Greatest of three numbers in Java using ternary operator is 23

If you look at the last case, it seems this program has some bugs, it doesn't return the correct value if all three numbers are equal, at least the first method. 

Can you modify this program to return the number itself if all three integers are same? for example in this case it should return 23. 

For your help, I have implemented that logic in the second version of that function, which finds largest of three numbers using ternary operator.


That's all about how to find the maximum of three numbers in Java. We have also learned about use of ternary operators to solve this problem. If you are absolute beginner and face problem understanding logic, I suggest to take a look at the flowchart to find largest of three numbers. 

It's much easier to understand a flowchart than all description. It's said for nothing that, a picture is worth more than thousand words :). 

If you love to learn by solving coding problems, here are some of them to try your hands.


Coding Problems to learn Programming
Write a program to find Greatest Common Divisor of two numbers (solution)
Write a program to check if number is power of two (solution)
Write a program to swap two numbers without using third variable (answer)
How to find middle element of linked list in one pass? (solution)
How to find loop in linked list? (answer)

And now its your turn to answer question? What is your favorite coding exercise in Java? Prime numbers, Fibonacci, factorial, palindrome or  this one?

12 comments :

Martin Thoma said...

Wouldn't it be much easier to read when you used two times Math.max? Also, one could easily see how to generalize it for n numbers

Dipika Mulchandani said...

First, we assume that first is the maximum number and therefore initialize max with a. Now, we check if second is greater than max ( first ). If yes, we set max to second. Now, max holds the greater of the two numbers : first and second.

Wouldn't this simplify the code?

int max = first;
if (second > max) {
max = second;
}
if (third > max) {
max = third;
}

Unknown said...

int max(int a, int b, int c) {
return a > b && a > c ? a : b > c ? b : c;
}

Anonymous said...

it can be stored in collection, then do the sorting, then get the first value from it.

Anonymous said...

Yes, with SortedSet I did it in two lines of code.

Anonymous said...

Int a,b,c;
If (a>b)
b=a;
If (b>c)
Max=b;
Else
Max=c;

Simplest logic ever ...

Anonymous said...

Or maybe:
return Math.max(a, Math.max(b,c));

Cheers

Anonymous said...

int a = 16; int b = 11;int c = 12;
int max = Integer.MIN_VALUE;
if (a > max){
max=a;
}
if (b > max){
max=b;
}
if (c > max){
max=c;
}
System.out.println("max : "+max);

mohan said...

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {

public static void main(String[] args) {
List list=new ArrayList();
list.add(100);
list.add(50);
list.add(200);
Collections.sort(list);
System.out.println("MAX VALUE:"+list.get(0));
System.out.println("MIN VALUE:"+(list.get(list.size()-1)));
}

}

Unknown said...

A user enters a million of numbers, how can you get the result of the min and max values at the end?

javin paul said...

@Huy, you can use the same algorithm, don't you. Sorry if I don't see your point but in order to find the min and max, you need to keep two variable and compare every number with them e.g. if next number is larger than max than update max, else if its smaller than min than update min or else do nothing.

if( number > max){
max = number;
}else if(number < min){
min = number;
}

Anonymous said...

"Can you modify this program to return the number itself if all three integers are same? for example in this case it should return 23."
If you use >= instead of > it should work

Post a Comment