How to find the minimum and maximum number in java

Given java code snippet is to find the minimum and the maximum number from the given array of integers.
public class FindMinAndMax {
    public static void main(String[] args) {
        int[] numbers = { 2, 4, 5, 33, 34, 423 };
        int max = numbers[0];
        int min = numbers[0];
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] < min)
                min = numbers[i];
            else if (numbers[i] > max)
                max = numbers[i];
        }
        System.out.println("Min Number" + "\t" + "Max Number");
        System.out.print(min + "\t\t" + max);

    }
}

Output:


Min Number    Max Number
2                    423

No comments:

Post a Comment