Friday, July 14, 2017

One of the classical program to build programming logic is, write a program to find largest of three numbers. I am sure many of you have already done this exercise in 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 flowchart of largest of three numbers and then we will implement solution using 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 ternary operator works, as one of the popular version of this require you to find largest of three numbers using ternary operator.
This problem is in similar category as how to determine if number is prime. This Java program finds 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 other 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 largest of a list of numbers say 10 integers then using above approach is not easy, instead you can use array data structure, and keep track of largest number while comparing with other numbers.

We will also see how we can use ternary operator in Java to find 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 main method directly, without creating object of this class.

Logic to find Greatest of Three Integers

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 ternary operator, as it has three arguments, that's why it can only be applied to languages which supports ternary operator e.g. Java. Logic to find biggest of three number is as follows :

Check if first number is greater than second and third, if Yes, then first number is largest.

Check if second number is greater than second and third, if Yes, the second number is largest.

Otherwise, third number is 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 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 largest of three numbers in Java, it first reads three numbers A, B and C from console, using utilities like Scanner. Then it first compare A against B, if A > B then it goes to compare A and C. If A > C, the A is largest number, else C is maximum number. On the other hand, if A < B in first comparison then second comparison happens between B and C, if B > C then B is largest otherwise C is largest number. This logic is shown in below flowchart, I am sure its much easier to understand a flowchart then its description :)

Complexity of Our Solution

If you look at the flow chart, you will find that we at-least needs to do two comparison to find 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 maximum of three numbers, we have done 2 comparisons, which means to find maximum of n numbers, we need to do n-1 comparison. That's why 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 solution, one which finds largest of three numbers using ternary operator and other which uses if-else-if loop. First solution is very simple as it compares numbers more than required, in worst case it does 8 comparisons. Second solution uses the logic from flowchart and only does two comparison 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 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.

importjava.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
*/publicclassLargestOfThree{
publicstaticvoidmain(String args[]) {
Scanner cmd =newScanner(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.
*/publicstaticintlargestOfThree(int first, int second, int third) {
if (first > second && first > third) {
return first;
} elseif (second > first && second > third) {
return second;
} elseif (third > first && third > second) {
return third;
}
returnInteger.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
*/publicstaticintgreatestOfThreeUsingTernaryOperator(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
112131Largest of three numbers, between 11, 21 and 31 is 31Greatest of three numbers in Java using ternary operator is 31Please enter three different numbers to find largest of them
454Largest of three numbers, between 4, 5 and 4 is 5Greatest of three numbers in Java using ternary operator is 5Please enter three different numbers to find largest of them
232323Largest of three numbers, between 23, 23 and 23 is -2147483648Greatest 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 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 maximum of three numbers in Java. We have also learned about use of ternary operator to solve this problem. If you are absolute beginner and face problem to understand 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)

12 comments
:

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.

@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.