maximum element in array

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

Example:-

If n=4(size of an array)

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

Steps:-

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

Java code to print maximum element in array.

package gangforcode;
import java.util.Scanner;
public class MaxinArr {
public static int maximum(int[] arr) {
	int max = Integer.MIN_VALUE;
	for(int i=0;i<arr.length;i++) {
		if(max<arr[i]) {
			max=arr[i];
			
		}
	}
	return(max);
}
	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("Largest in given array is"+" "+ maximum(arr));
		
		
	}

}

Output:-

maximum element in an array

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

Leave a Comment