Technical SpeaksCodeForDevelopersThe official blog of Technical Speaks
Core Java

How to find max and min in array in java Using Scanner Class

By · Published · Updated · 1 min read

How to find max and min in array in java

In java there is no any built-in functions for finding minimum and maximum values of an array, and to find that we would have to code by ourself;

Before going to start Coding, if you don’t know the basics about Arrays in Java then watch this video below first:

1. Java Program to find the minimum element of an array:

code
import java.util.Scanner;

public class ArrayMin{
public static void main(String[] args){
		
int n, min;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no of elements in Array");
n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter elements in Array");
for(int i =0; i< n; i++){
a[i] = sc.nextInt();
}
min = a[0];
for(int i =0; i< n; i++){
if(min > a[i]){
min = a[i];
}
}
System.out.println("Minimum Element is " +min);

}	
}

Result:

how-to-find-min-element-in-array-java

2. Java Program to find the maximum element of an array:

code
import java.util.Scanner;

public class ArrayMin{
public static void main(String[] args){
		
int n, max;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no of elements in Array");
n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter elements in Array");
for(int i =0; i< n; i++){
a[i] = sc.nextInt();
}
max = a[0];
for(int i =0; i< n; i++){
if(max < a[i]){
max = a[i];
}
}
System.out.println("Maximum Element is " +max);

}	
}

Result:

Written by

Saurabh Kumar

SEO Consultant and Founder of Technical Speaks

Saurabh Kumar is an SEO professional with more than 10 years of hands-on experience and a Top Rated freelancer on Upwork. He is the founder of Technical Speaks and also builds websites with Next.js and WordPress.

Comments

Leave a comment