Java Program to find Smallest Element in an Array

In this post we will go through the process of finding the smallest element in an array using Java.

Smallest Element in an Array :

An array is a data structure that allows you to store multiple values of the same type in a single variable. It’s like a container that holds a collection of elements.

Each element in the array is assigned a unique index, starting from 0,

which allows you to access and manipulate individual elements.

Problem :

simple example of the problem –

Example 1 :

Input  arr[] = {12, 56, 45, 34, 30}

Output :  12

Explanation 1:

The smallest element of the given array is 12.

Example 2 :
Input : arr[] = {2, -1, 9, 10}
output : -1

Explanation 2:

The smallest element of the given array is -1.

Solution :

Algorithm :

1 Create and initialize an array.

2. Start by assuming the first element of the array is the smallest and store it in a variable called “min”.

3.  Go through each element of the array one by one.

4.  Compare each element with the current “min” value.

5.  If you find an element smaller than the current “min”, update the value of “min” to that element.

6.  Keep repeating steps 3 and 4 until you have checked all the elements in the array.

7.  After checking all the elements, the variable “min” will hold the smallest element.

8.  Print the value of “min” to display the smallest element.

class SearchMin{
    public static void main(String[]args){
        int a[]={32,57,63,55,48};
        int min=a[0];
        for(int i=0;i<a.length;i++){
            if(a[i]<min){
                a[i]=min;
            }
        }
            System.out.println("The smallest element of the given array is "+min);        
    }
}
Output :
The smallest element of the given array is 32

 

 

Leave a Comment

%d bloggers like this: