Write a Java Program to Find the Largest and Smallest Array Number with an example. Or how to write a Java Program to find the largest and smallest element or item in a given array.
This Java smallest and largest array number example uses Else If statement. The first If statement checks and finds the smallest number, and the else if finds the largest number. Please refer to the Java Largest Array Number and Java Smallest Array Number articles.
package ArrayPrograms;
import java.util.Scanner;
public class LargestSmallestArrayItem1 {
private static Scanner sc;
public static void main(String[] args) {
int Size, i, Largest, Smallest, min_Position = 0, max_Position = 0;
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the SMLRG Array size = ");
Size = sc.nextInt();
int[] smlLrg_arr = new int[Size];
System.out.format("\nEnter SMLRG Array %d elements = ", Size);
for(i = 0; i < Size; i++) {
smlLrg_arr[i] = sc.nextInt();
}
Smallest = smlLrg_arr[0];
Largest = smlLrg_arr[0];
for(i = 1; i < Size; i++) {
if(Smallest > smlLrg_arr[i])
{
Smallest = smlLrg_arr[i];
min_Position = i;
}
else if(Largest < smlLrg_arr[i])
{
Largest = smlLrg_arr[i];
max_Position = i;
}
}
System.out.format("\nLargest element in SMLRG Array = %d", Largest);
System.out.format("\nIndex position of the Largest element = %d", max_Position);
System.out.format("\n\nSmallest element in SMLRG Array = %d", Smallest);
System.out.format("\nIndex position of the Smallest element = %d", min_Position);
}
}
OUTPUT
Java Program to Find Largest and Smallest Array Number example 2
In this Java code for smallest and largest array item example, we created separate functions to find and return the smallest and largest items in the given array.
package ArrayPrograms;
import java.util.Scanner;
public class LargestSmallestArrayItem2 {
private static Scanner sc;
static int Size, i, Largest, Smallest, min_Position = 0, max_Position = 0;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the SMLRG Array size = ");
Size = sc.nextInt();
int[] smlLrg_arr = new int[Size];
System.out.format("\nEnter SMLRG Array %d elements = ", Size);
for(i = 0; i < Size; i++) {
smlLrg_arr[i] = sc.nextInt();
}
LargestElement(smlLrg_arr);
SmallestElement(smlLrg_arr);
}
public static void LargestElement(int[] lrg_arr ) {
Largest = lrg_arr[0];
for(i = 1; i < Size; i++) {
if(Largest < lrg_arr[i]) {
Largest = lrg_arr[i];
max_Position = i;
}
}
System.out.format("\nLargest element in SMLRG Array = %d", Largest);
System.out.format("\nIndex position of the Largest element = %d", max_Position);
}
public static void SmallestElement(int[] sm_arr ) {
Smallest = sm_arr[0];
for(i = 1; i < Size; i++) {
if(Smallest > sm_arr[i]) {
Smallest = sm_arr[i];
min_Position = i;
}
}
System.out.format("\n\nSmallest element in SMLRG Array = %d", Smallest);
System.out.format("\nIndex position of the Smallest element = %d", min_Position);
}
}
OUTPUT