Largest and Smallest Number in Array
Here you will get the example code to find the largest and smallest number in array java program.
In this program, First we will take some numbers from the user as input and store in an Array list, After that we will find the Largest and Smallest Number in Array using for loop.
Largest and Smallest Number in Array Java Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import java.util.*; public class ArrayLargestSmallest { public static void main(String args[]) { int i, Largest, Smallest; Scanner sc = new Scanner(System.in); //Input how many elements System.out.print("Enter number of elements : "); int num=sc.nextInt(); int arr[]=new int[num]; // input Array elements System.out.print("Enter elements of array : "); for (i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } Largest=arr[0]; Smallest=arr[0]; //Find smallest and largest number for (i = 0; i < arr.length; i++) { if(arr[i] > Largest) Largest = arr[i]; else if (arr[i] < Smallest) Smallest = arr[i]; } System.out.print("\nLargest number is : "+Largest); System.out.print("\nSmallest number is : "+Smallest); } } |
Output
Check out our other Java Programming Examples