Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find smallest element of an Array .

Java Code Example — Array Programs

ADVERTISEMENT

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

  1. Use a Scanner to read the desired array size n from the user.
  2. Initialize a new array arr of size n.
  3. Use a for loop to read n integers from the user into the array.
  4. Pass the array to a method min().
  5. Initialize min = a[0].
  6. Loop through the array, updating min whenever an element a[i] < min is found.
  7. 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 &gt; to &lt;.
  • By encapsulating the search logic inside the min() method, the main method 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.
ADVERTISEMENT