This post of To find largest and smallest number in the given Array is about writing a Java program to find the largest and the smallest number in the given input Array or it can also be rephrased as – Find the maximum and minimum number in the given array.
Condition here is that you should not be using any inbuilt Java classes (i.e. Arrays.sort) or any existing data structure.
You may also like –
Java Program to find duplicate elements in an Array
In this logic We have two variables for maximum and minimum number, initially assign the element at the first index of the array to both the variables.
Then loop or iterate the array and compare each array element with the max number if max number is less than the array element then assign array element to the max number.
If max number is greater than the array element then we have to check if minimum number is greater than the array element, if yes then assign array element to the minimum number.
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 |
package com.kkjavatutorials.client; /** * @author KK JavaTutorials * This java program is all about Hpw to find largest and smallest number in the given Array */ public class FindMaxAndMinElementInAnArray { public static void main(String[] args) { int inputNumArray[] = { 12, 39, 1008, 127, 89, 2987,16,28, 123,787,54 }; //Start by assigning the first array element to both the variables int maxNumber = inputNumArray[0]; int minNumber = inputNumArray[0]; //Start with next index (i.e. i = 1) for (int i = 1; i < inputNumArray.length; i++) { if (maxNumber < inputNumArray[i]) { maxNumber = inputNumArray[i]; } else if (minNumber > inputNumArray[i]) { minNumber = inputNumArray[i]; } } System.out.println("Largest number:" + maxNumber + ", Smallest number:" + minNumber); } } |
Output of Above Example:
1 |
Largest number:2987, Smallest number:12 |
That’s all about topic How to find largest and smallest number in the given input Array. If you have any doubts or any suggestions to make please drop a comment.