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.
No comments:
Post a Comment