In this article, we are going to find maximum and minimum element in the given array using java code.
Example:-
if n=4(size of an array)
arr={48,58,5,2}, then the output will be 58 is the maximum element and 2 is the minimum element.
steps:-
- Take array input from user using scanner.
- Take a variable min and initialize it with maximum possible value.
- Take another variable max and initialize it with minimum possible value.
- Run a loop to iterate elements of array.
- inside the array check if min is greater then array element then update min with array element else update max with array element.
- end of loop.
- variable max and min will be hold the maximum and minimum element in array.
Java code to find maximum and minimum element in an array:-
package gangforcode;
import java.util.Scanner;
public class MinArray {
public static void maxmin(int[] arr) {
int min = Integer.MAX_VALUE;
int max= Integer.MIN_VALUE;
for(int i=0;i<arr.length;i++) {
if(min>arr[i]) {
min=arr[i];
}else {
max=arr[i];
}
}
System.out.println("minimum element in the array is "+min);
System.out.println("maximum element in the array is "+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();
}
maxmin(arr);
}}
Output:-
You can use the same logic to find minimum and maximum element in array using other programing languages like C, C++, Python etc.