Saturday, September 16, 2023

How to Find the Largest and Smallest of Three Numbers in Java? [Solved]

Hey Java programmers, I have been sharing coding problems from interviews for quite some time and 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 skills then these kinds of small problems are good to start with. They not only provide you an opportunity to think about how to solve a problem using basic programming constructs like conditionals (if, else, if-else, switch), loops (for, while, do-while), operators like arithmetic, the bitwise and logical operators 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 the Given Three Numbers. 

This means you need to write a Java program and function which takes three numbers and prints 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 a 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 that works fine for integers does not necessarily 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 write the unit test or you can pass three numbers from the console or directly and then print. The 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 it in Python or if you are a C++ programmer you can solve it 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 the 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 Alphabet first before learning speaking or writing.





Logic to Find the Maximum and Minimum of Three Integer

Now that we have understood the problems, decided on 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 largest number of given three numbers and others to find the smallest of three numbers.


So, we have the largest(int first, int second, int thirdwhich will calculate the largest of three, and smallest(int first, int second, int third) which will calculate the 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 the second is greater than the 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 the max. If yes, we set the 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 the console in Java or how to display the result in the 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




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 


You can see that our program is working fine and able to calculate both the maximum and minimum of three numbers in Java. The logic in this problem is simple but just knowing how to use operators in a  correct way helps a lot. 

If you are serious about doing well on coding interviews then I also suggest you join Grokking the Coding Interview: Patterns for Coding Questions course on Educative, an interactive course to learn essential coding patterns like sliding window, fast and slow pointers, merge intervals, etc which can be used to solve 100+ Leetcode problems. It's a unique course and dI highly recommend it to anyone who wants to master solving coding problems. 

best course for coding interviews



That's 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 flowchart, 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. 


If you need more Coding problems from Practice, here are a 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 the 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 the word of a sentence in Java? (solution)
  • How to find if the 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 it 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.

Now, it's time for  question for you, What is your favorite coding exercise? Palindrom, reverse an int, or this question? Do let me know in comments. 

4 comments:

  1. *Mid Semester Take Home Exam*
    1. Write a Java program that generates random numbers with your ID as the Class Name.
    Use a Do-While loop and a method to display a Menu Interface with the following options
    1 - Register
    2 - View
    When the user selects option 1:
    The program must ask the user to register by taking the following details with the help of a method called Register
    a. Index Number
    b. First Name
    c. Last Name
    d. Department
    e. Level
    f. Age
    This information must be written to a text file called Random Numbers.
    The program must now use a For loop to generate the random numbers with the users age as the seed in the following format: XXXX - XXXX - XXXX (where X can be any alphanumeric character)

    When the user selects option 2:
    The program asks for the users Index Number
    The program checks if a random number has been generated for the user previously in the text file.
    If Yes: the program displays the Random Number
    If No: the program displays an error message using Try-Catch and displays the menu screen again.

    Any help with this assignment please??

    ReplyDelete
  2. Hello,

    Thank for the great example! Is there a way also to add to it a way of swapping the biggest and smallest among the inserted 3 values?

    Thank you in advance!

    ReplyDelete
    Replies
    1. Yes, you can swap by adding swap function.

      //Code for swapping two numbers

      void swap(int largest, int smallest){
      int temp = smallest;
      smallest=largest;
      largest=temp;
      }

      Delete

Feel free to comment, ask questions if you have any doubt.