Java Program to find smallest element of an Array .
Objective
Write a Java program to find the smallest element of an array, taking user input for size and elements.
Algorithm / Approach
- Use a
Scannerto read the desired array sizenfrom the user. - Initialize a new array
arrof sizen. - Use a
forloop to readnintegers from the user into the array. - Pass the array to a method
min(). - Initialize
min = a[0]. - Loop through the array, updating
minwhenever an elementa[i] < minis found. - Print the smallest element.
Test.java
import java.util.Scanner;
class Test {
void min(int[] a){
int min = a[0];
for(int i=0; i< a.length; i++) {
if(min>a[i]) {
min = a[i];
}
}
System.out.print("Smallest = "+min);
}
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Array Size: ");
int n = s.nextInt();
int arr[] = new int[n];
System.out.print("Enter Elements: ");
for(int i=0;i < n; i++) {
arr[i] = s.nextInt();
}
Test t = new Test();
t.min(arr);
}
}
Expected Output
Enter Array Size: 5 Enter Elements: 12 15 11 92 34 Smallest = 11
Explanation of the Program
- This program demonstrates dynamic array initialization where the size is determined at runtime based on user input.
- The logic to find the minimum is identical to finding the maximum, just with the comparison operator flipped from
>to<. - By encapsulating the search logic inside the
min()method, themainmethod remains clean and focused solely on handling I/O.
Complexity
Time Complexity
O(n) - One pass for reading input, one pass for finding the minimum.
Space Complexity
O(n) - To store the array elements in memory.