How to Find the Largest and Smallest of Three Numbers in Java

Hello guys, today, I am going to share with you another interesting coding problem for beginners, how to find the largest and smallest of three numbers. If you are learning how to program or looking to improve your problem-solving and coding skill then these kind of small problems are good to start with. They not only provide you an opportunity to think how to solve a problem using basic programming constructs like conditionals (if, else, if-else, switch), loops (for, while, do-while), operators like arithmetic, bitwise and logical operator as well as teach you how to write functions, class and create a program which you can run.

Now that you understand the purpose of these small coding problems, let's first understand the problem better, a good approach before jumping into the solution.

Problem: Write a Program to find the Maximum and Minimum of Given Three Numbers. 

This means you need to write a Java program and function which takes three numbers and print the largest and smallest of them.

For the sake of simplicity, we can assume that we are dealing with integers as the number can be floating point also, but you should always get clarified what kind of data you are dealing with, as they are very important to find the right solution. A function which works fine for integer not necessary work for long or float, especially in a production environment.

Now, another question is how do you pass those three numbers? Well, you can either right Unit test or you can pass three numbers from the console or directly and then print. First one is completely programmatic and a better approach, but the second one is interactive and good when you are learning.  Since the problem is simple, I'll follow the second approach here.

Btw, you also need to decide which programming language you are going to solve the problem. If you know Python well, you can solve in Python or if you are a C++ programmer you can solve in C++, there is no restriction on that.

Since I am a Java developer, I'll solve this problem in Java. I assume that you know basics of Java, but if you don't, you should first go through a good Java course like The Complete Java Masterclass on Udemy before solving Coding problems. Just like we learn the Alphabets first before learning speaking or writing.




Logic to Find the Maximum and Minimum of Three Integer

Now that we have understood the problems, decided the programming language to solve the problem, it's time to think about the logic for solving this problem.

Since we need to return both the largest and smallest of three numbers, we'll solve this in two parts. We would need two methods, one to calculate the larget number of given three numbers and others to find the smallest of three numbers.


So, we have largest(int first, int second, int thirdwhich will calculate largest of three, and smallest(int first, int second, int thirdwhich will calculate smallest of three. But, how? let's understand the logic.

We'll use a variable max or min to hold the current max number while we are doing the calculation. First, we assume that the first number is the maximum number and therefore initialize max with first.

Now, we check if second is greater than max. If yes, we set max to second. Now, max holds the largest of the two numbers: first and second. Next, we check if the third is greater than max. If yes, we set max to third. So, finally, max holds the largest of the three numbers.

Similarly, we find the least number of three and display the result. If you are wondering how to read the user input from console in Java or how to display the result in console, I have used Scanner and System.out.println() methods for those purposes. If you don't know about them, I suggest you go through a fundamental course like Java Fundamentals Part 1 and 2 on Pluralsight to learn them better. 

How to Find the Largest and Smallest of Three Numbers  in Java



Program to find the Largest and Smallest of three Integers

Here is the complete Java program to find the maximum and minimum of giving three integers:

 
import java.util.Scanner;
 
/*
 * Java Program to find largest and smallest of three numbers
 */
public class Main {
 
    public static void main(String args[]) {
 
        // creating scanner to accept radius of circle
        Scanner scanner = new Scanner(System.in);
        System.out.println("Welcome in Java program to find largest 
                     and smallest of three numbers");
 
        System.out.println("Please enter first number :");
        int first = scanner.nextInt();
 
        System.out.println("Please enter second number :");
        int second = scanner.nextInt();
 
        System.out.println("Please enter third number :");
        int third = scanner.nextInt();
 
        int largest = largest(first, second, third);
        int smallest = smallest(first, second, third);
 
        System.out.printf("largest of three numbers %d, %d, and %d is : %d %n",
                                   first, second, third, largest);
        System.out.printf("smallest of three numbers %d, %d, and %d is : %d %n", 
                               first, second, third, smallest);
 
        scanner.close();
    }
 
    /**
     * Java method to calculate largest of three numbers
     *
     * @param first
     * @param second
     * @param third
     * @return maximum or largest of three
     */
    public static int largest(int first, int second, int third) {
        int max = first;
        if (second > max) {
            max = second;
        }
 
        if (third > max) {
            max = third;
        }
 
        return max;
    }
 
    /**
     * Java method to calculate smallest of three numbers
     *
     * @param first
     * @param second
     * @param third
     * @return minimum or smallest of three
     */
    public static int smallest(int first, int second, int third) {
        int min = first;
        if (second < min) {
            min = second;
        }
 
        if (third < min) {
            min = third;
        }
 
        return min;
    }
}
 
 
Output
 
Welcome in Java program to find the largest and smallest of three numbers
 
Please enter the first number :
 
1
 
Please enter the second number :
 
2
 
Please enter the third number :
 
3
 
largest of three numbers 1, 2, and 3 is : 3 
 
smallest of three numbers 1, 2, and 3 is: 1 


That' all about how to find the largest and smallest of three numbers in Java. If you have any trouble understanding logic or executing this program, please drop a note and I would be happy to help. You can also check the flow-chart, which helps to visualize the logic. If you like these kinds of coding problems and if they have helped in learning to code then please share with your friends and colleagues. 

Further Learning
The Complete Java MasterClass
Data Structures and Algorithms: Deep Dive Using Java



If you need more Coding problems from Practice, here are few more to explore
  • 100+ Data Structure Problems from Interviews (questions)
  • Top 10 Programming problems from Java Interviews? (article)
  • How to calculate factorial using recursion and iteration? (solution)
  • 20+ String based Problems from Programming Interviews (questions)
  • How do you swap two integers without using a temporary variable? (solution)
  • Write a program to check if a number is a power of two or not? (solution)
  • 50+ Algorithms based Problems for Java Programmers (questions)
  • How to find duplicate characters from String in Java? (solution)
  • Write code to implement Quicksort algorithm in Java? (algorithm)
  • How to reverse String in Java without using StringBuffer? (solution)
  • 10 Free Algorithms Courses for Java developers (courses)
  • Write a program to code insertion sort algorithm in Java (program)
  • How to find a missing number in a sorted array? (solution)
  • How to solve the FizzBuzz problem in Java? (solution)
  • 10 Data Structure Courses to Crack Coding Interviews (courses)
  • How do you reverse word of a sentence in Java? (solution)
  • How to find if given String is a palindrome in Java? (solution)
  • How to reverse an int variable in Java? (solution)
  • Top 75 Programming Interview Questions for Java Programmers (questions)
  • Write a program to print the highest frequency word from a text file? (solution)
  • Write code to implement the Bubble sort algorithm in Java? (code)
  • How to check if a given number is prime or not? (solution)
  • How to remove duplicate elements from ArrayList in Java? (solution)
  • How to check if a year is a leap year in Java? (answer)
  • Java Program to print Prime numbers up to 100 (solution)
  • Java Program to print Alphabets in upper and lower case? (solution)
Thanks for reading this article so far. If you like this article then please share with your friends and colleagues.

P. S. - If you are looking to learn Data Structure and Algorithms from scratch or want to fill gaps in your understanding and looking for some free courses, then you can check out this list of Free Algorithms Courses on FreeCodeCamp to start with.

No comments:

Post a Comment