Java Online Compiler
Example: Java Program to Find Smallest and Largest Element in an Array using For loop
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// 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"); } }
9 4 35 53 53 54 252 3 534 34
Output
Clear
ADVERTISEMENTS