minimum element in array

In this article, we are going to find minimum element in array using java code.

Example:-

If n=4(size of an array)

arr={5,8,9,4}, then the output will be 4.

Steps:-

  • Take array as input from user using scanner.
  • Take a variable min and initialize it with maximum possible value.
  • Run a loop to iterate array element.
  • Inside loop compare min and element of array, if min> array elements then update max with array element.
  • End of loop.
  • min will be the smallest element in the array.

Java code to print minimum element in array.

public class MinArray {

	public static int minimum(int[] arr) {
			int min = Integer.MAX_VALUE;
			for(int i=0;i<arr.length;i++) {
				if(min>arr[i]) {
					min=arr[i];
					
				}
			}
			return(min);
		}
	public static void main(String[] args) {
		Scanner sc= new Scanner(System.in);
		System.out.println("Enter the size of array");
		int n=sc.nextInt();
		int[]arr=new int[n];
		for(int i=0;i<n;i++) {
			arr[i]=sc.nextInt();
		}
		System.out.println("minimum element in given array is"+" "+ minimum(arr));
	}}

Output:-

minimum element in array

You can use the same logic to print minimum element in an array using other programing languages like C, C++, python etc.

Leave a Comment