Java Online Compiler
Example: FindLargestAndSmallestUsingIteration in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// FindLargestAndSmallestUsingIteration import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { int[] numbers = {12, 5, 8, 20, 3, 15}; // Example array // Step 1: Initialize max and min with extreme values // Integer.MIN_VALUE and Integer.MAX_VALUE are used // to ensure any array element will be correctly identified // as either larger than current max or smaller than current min. int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; // Step 2: Iterate through the array for (int i = 0; i < numbers.length; i++) { // Step 3: Compare current element with max if (numbers[i] > max) { max = numbers[i]; // Update max if current element is larger } // Step 4: Compare current element with min if (numbers[i] < min) { min = numbers[i]; // Update min if current element is smaller } } // Step 5: Print the results System.out.println("Array elements: " + java.util.Arrays.toString(numbers)); System.out.println("Largest element: " + max); System.out.println("Smallest element: " + min); } }
Output
Clear
ADVERTISEMENTS