In this tutorial, you will learn how to write a java program to find the smallest element in an array. In theory, a smallest element in an array can be found by, copying the first element of the array in a variable smallestElement
(you can give any name to this variable). Then comparing that variable with rest of the elements, if any element is found smaller than the smallestElement
then store the value of that element into the variable. Repeat the process until all the elements are compared.
Program to find the smallest number in an array
In the following example, we have an array arr
of numbers. We have copied the first element of this array into a variable smallestElement
, this is to compare the other elements of the array to it. This is just the initialization of this variable, at the end of the program, this variable will hold the smallest number present in the array.
Running a loop from 0 till arr.length
(this represents the size of the array). At every loop iteration, each element of the array is compared with the smallestElement
, if any element is smaller than smallestElement
, then the value of that element is assigned to smallestElement
. This process continues until the whole array is traversed.
In the end, the variable smallestElement
holds the smallest element of the given array.
public class JavaExample { public static void main(String[] args) { //Initializing an int array int [] arr = new int [] {3, 8, 1, 12, 7, 99}; //This element will store the smallest element of the array //Initializing with the first element of the array int smallestElement = arr[0]; //Running the loop from first element till last element for (int i = 0; i < arr.length; i++) { //Compare each elements of array with smallestElement //If an element is smaller, store the element into smallestElement if(arr[i] < smallestElement) smallestElement = arr[i]; } System.out.println("Smallest element of given array: " + smallestElement); } }
Output:
Smallest element of given array: 1
Leave a Reply