Java Code for finding the Smallest Element in an Array

Finding the Smallest element of the array

An array is a data structure which stores the similar type of data. Here we are considering an integer array, which has some elements in it and we will write a Java Program for finding the smallest element of the array

Java Program to find the smallest element in the array(1)

Algorithm for Finding the smallest element of the array

  • Step 1 – Initialize len,min.
  • Step 2 – Accept the length of the array.
  • Step 3 – Initialize an array.
  • Step 4 – Accept the input, using for loop.
  • Step 5 – Store the first element of the array in min.
  • Step 6 – Compare all the elements of the array with min, and use a if condition for comparing all the array elements with min.
  • Step 7 – If there’ll be any element smaller than min, store it value in min.
  • Step 8 – Print min.

JAVA Program for finding the smallest number in an array

import java.util.*;
class prep {
  public static void main(String[] args) {
    int len,min=0;
    System.out.println("Enter the length of the array");
    Scanner sc=new Scanner(System.in);
    len=sc.nextInt();
    int[] arr=new int[50];
    System.out.println("Enter the elements of the array");
    for(int i=0;i<len;i++)
    {
      arr[i]=sc.nextInt();
      min=arr[0];
      if(arr[i]<min)
      min=arr[i];
    }
    System.out.println("The smallest element of the array is "+min);
  }
}
Output

Enter the length of the array

5

Enter the elements of the array

5

4

3

2

1

The smallest element of the array is 1