Java Program to print the smallest element in an array

In this program, we aim to determine the smallest element in an array. We can accomplish this by using a variable called “min” which is initially assigned the value of the first element in the array. By iterating through the array, we compare the value of “min” with each element. If any element’s value is found to be smaller than the current value of “min,” we update the value of “min” with that element. The goal is to find the smallest element in the array by continuously updating “min” whenever a smaller value is encountered.

In the given array, the initial value of “min” is set to 25. During the first iteration, “min” is compared to 11. Since 11 is smaller than the current value of “min,” the value of “min” is updated to 11. In the second iteration, 11 is compared to 7. As 7 is smaller than the current value of “min,” “min” is updated to 7. This process continues until the end of the array is reached. Ultimately, “min” will hold the smallest value present in the array.

Algorithm for a Java Program to print the smallest element in an array

STEP 1: START
STEP 2: Initialize the array arr[] with values {25, 11, 7, 75, 56}
STEP 3: Set the variable min to the value of arr[0]
STEP 4: Repeat steps 5 to 7 for each element in the array (index i starting from 0 and incrementing until i is less than the length of arr[])
STEP 5: Check if the current element arr[i] is less than the value of min
STEP 6: If the condition in step 5 is true, update the value of min to arr[i]
STEP 7: Continue to the next iteration
STEP 8: Print the message “Smallest element in the given array:”
STEP 9: Print the value of the min
STEP 10: END

Java Program to print the smallest element in an array

public class SmallestElement_array {  
    public static void main(String[] args) {  
  
        //Initialize array  
        int [] arr = new int [] {25, 11, 7, 75, 56};  
        //Initialize min with first element of array.  
        int min = arr[0];  
        //Loop through the array  
        for (int i = 0; i < arr.length; i++) {  
            //Compare elements of array with min  
           if(arr[i] <min)  
               min = arr[i];  
        }  
        System.out.println("Smallest element present in given array: " + min);  
    }  
}

Output:

Smallest element present in given array: 7

To conclude, the provided Java program aims to find and print the smallest element in an array. It accomplishes this by initializing a variable, min, with the value of the first element in the array. By traversing the array using a loop, each element is compared with the current value of min. If an element is found to be smaller, the value of min is updated accordingly. Follow tutorials.freshersnow.com to learn more.