Find Maximum and Minimum of numbers

Maths confusion, finding max and min
For days I had been stumped to find maximum and minimum of 3 numbers which is nothing more than a simple logic. I felt laughed at myself. Now no more such ridicule. Math.max() and Math.min() the methods that find only maximum and minimum of 2 numbers. However, with a simple trick, we can get the maximum of as many numbers as we want. In this example, i will be showing you how to find maximum and minimum of three numbers. But before that let us take a look at the prototype of these methods.

public int max(int,int)
public int min(int,int)

Note that there are overloaded versions of these methods which differ in type. As these methods doesn't depend upon any member variables of the class, it is declared static, so can be accessed directly via the class name.


import java.util.*;
class MaxMin
{
    public static void main(String args[])
    {
        Scanner s=new Scanner(System.in);
       
        System.out.println("Enter three numbers");
       
        // Take three ints
        int a=s.nextInt();
        int b=s.nextInt();
        int c=s.nextInt();
       
        // Two is just common, let's try three!
       
        // Math.max(a,b) gives maximum of a,b
        // Then the Math.max(maximum of a and b,c) gives
        // the maximum value of a,b,c
        int max=Math.max(Math.max(a,b),c);
       
        // Math.min(a,b) gives minimum of a,b
        // Then the Math.max(minimum of and b,c) gives
        // the minimum value of a,b,c
        int min=Math.min(Math.min(a,b),c);
       
        // Print them
        System.out.println("Maximum number "+max);
        System.out.println("Minimum number "+min);
       
    }
}

If you want the maximum for 4 numbers, then you would write,

int max=Math.max(Math.max(Math.max(a,b),c),d);

But isn't it ridiculous to make these many method calls, when we can do it our own. It is ok, for finding maximum of 3-4 numbers, in case of an array our own logic is preferred. Here is how to find largest number in an array.

One more way will be using Arrays.sort(), this is dead simple and finds maximum and minimum of a lot of numbers. The last is the largest, first is the least. If you love this post, the trick and the bottom suggestion, please share it.
Image credit: relevantmath.blogspot.com

No comments: