Java Program to Find Smallest and Largest Element in an Array using For loop
ADVERTISEMENTS
Java program to find smallest and largest element in an array using for loop. In this article, you will learn how to make java program to find smallest and largest element in an array using for loop.
Source Code
// Java Program to Find Smallest and Largest Element in an Array using For loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x[], s, i, b, sm;
x = new int[50];
// x - To store array list of input numbers
// s - To store size of the array
// b - To store big element variable
// sm - To store small element variable
System.out.println ("\n-----Enter the size of the array-----\n");
s = in.nextInt();
System.out.println ("\n\n-----Enter the " + s + " elements of the array-----\n");
for(i = 0; i < s; i++) {
x[i] = in.nextInt();
}
// It stored first element of array to check the element
b = x[0];
for(i = 1; i < s; i++) {
// It checks one by one with each value of array
// To compare the value is smallest or largest
if(b < x[i]) {
b = x[i];
}
}
System.out.println ("\n-----The largest element is: " + b + "\n");
// It stored first element of array to check the element
sm = x[0];
for(i = 1; i < s; i++) {
// It checks one by one with each value of array
// To compare the value is smallest or largest
if(sm > x[i]) {
sm = x[i];
}
}
System.out.println ("\n-----The smallest element is: " + sm + "\n");
}
}
Output
-----Enter the size of the array-----
9
-----Enter the 9 elements of the array-----
4
35
53
53
54
252
3
534
34
-----The largest element is: 534
-----The smallest element is: 3