Java Program to Find Smallest Array Number

Write a Java Program to Find Smallest Array Number with an example. Or how to write a Java Program to print or return the smallest number in a given array.

In this Java smallest array number example, we allowed the user to enter the size and the sm_arr array items. Next, we assigned the first array item as the smallest, and next, we compared that value with other array items. If any other array item is less than that value, we replaced the smallest variable value with that array item.

package ArrayPrograms;

import java.util.Scanner;

public class SmallestElement {
	private static Scanner sc;
	
	public static void main(String[] args) {
		int Size, i, Smallest, Position = 0;
		int[] sm_arr = new int[10];
		
		sc = new Scanner(System.in);		
		System.out.print("\n Please Enter the size of an array  : ");
		Size = sc.nextInt();
		
		System.out.format("\nPlease Enter %d elements of an array: ", Size);
		for(i = 0; i < Size; i++) {
			sm_arr[i] = sc.nextInt();
		}
		Smallest = sm_arr[0];
		for(i = 1; i < Size; i++) {
			if(Smallest > sm_arr[i]) {
				Smallest = sm_arr[i];
				Position = i;
			}
		}
		System.out.format("\nSmallest element in an Array = %d", Smallest);
		System.out.format("\nIndex position of the Smallest element = %d", Position);
	}
}
Java Program to find Smallest Array Number 1

Java Program to Find Smallest Array Number example 2

In this Java smallest array item example code, we created a separate function that returns the smallest number from the given array. Please refer to the C Program to find the smallest Number in an Array article to understand the For loop iteration.

package ArrayPrograms;

import java.util.Scanner;

public class SmallestElementUsingMethod {
	private static Scanner sc;
	static int Size, i, Smallest, Position = 0;	
	public static void main(String[] args) {
		
		sc = new Scanner(System.in);		
		System.out.print("\nPlease Enter the SM Array size : ");
		Size = sc.nextInt();

		int[] sm_arr = new int[Size];
		System.out.format("\nEnter SM Array %d elements :  ", Size);
		for(i = 0; i < Size; i++) {
			sm_arr[i] = sc.nextInt();
		}
		Smallest = SmallestElement(sm_arr);
		System.out.format("\nSmallest element in SM Array = %d", Smallest);
	}
	public static int SmallestElement(int[] sm_arr ) {
		Smallest = sm_arr[0];
		for(i = 1; i < Size; i++) {
			if(Smallest > sm_arr[i]) {
				Smallest = sm_arr[i];
				Position = i;
			}
		}
		return Smallest; 
	}
}
Please Enter the SM Array size : 8

Enter SM Array 8 elements :  10 8 11 22 6 9 22 67

Smallest element in SM Array = 6