Array Java Programs

Find the largest and smallest number in Array

In this tutorial you will learn how to write a Java program to find the largest and smallest number in an array.

Below is the approach we will take to write our program:

  1. First, we will take the user’s input in an array and select the first element as the largest and smallest.
  2. Now we will go through each element of an array and compare it with the largest element (which we selected as the first element).
  3. Now when we find the largest element, we replace the old largest value with a new one and follow the same process until we have gone through all the elements of an array.
  4. When we find the next smaller element, we replace it with the old one and follow the same process until we have gone through all the array elements.

How will our program behave?

Our program will take an array and based on the logic it will output the largest and smallest number of an array.

Suppose we input an array with the values 34, 22, 1, 90, 114, 87. Then our program should give the following output: The largest number is 114The smallest number is 1

Find largest and smallest number in Java array

import java.util.*;

public class ArrayExample {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the size of array: ");
		int n = sc.nextInt();
		int arr[] = new int[n];
		System.out.println("Enter " + n + " array elements ");
		for (int i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}
		int largest = arr[0];
		int smallest = arr[0];
		for (int i = 1; i < n; i++) {
			if (arr[i] > largest) {
				largest = arr[i];
			}
			if (arr[i] < smallest) {
				smallest = arr[i];
			}
		}
		System.out.println(largest + " is largest and " + smallest + " is smallest");
	}
}

Output

Enter the size of array: 
8
Enter 8 array elements 
2
3
45
6
4
88
4
3
88 is largest and 2 is smallest

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs