Opening Hours :7AM to 9PM
class Smallest { public int findSmallest(int[] arr) { int smallest = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] < smallest) { smallest = arr[i]; } } return smallest; } } public class Main { public static void main(String[] args) { Smallest sm=new Smallest(); int[] arr = {1, 5, 3, 8, 2, 9, 4}; int smallest =sm. findSmallest(arr); System.out.println("The smallest element in the array is: " + smallest); } }This program uses a for-loop to iterate through the array and compares each element with the current smallest element. If an element is less than the current smallest, it becomes the new smallest element. The first element of the array is assumed as the smallest element before the loop starts.
public class Main { public static void main(String[] args) { int[] arr = {1, 5, 3, 8, 2, 9, 4}; Arrays.sort(arr); int smallest = arr[0]; System.out.println("The smallest element in the array is: " + smallest); } }In both examples, the output will be: