Program to find largest and smallest numbers among N numbers using an array

Hello all , I hope this blog is helping the readers to solve the issue facing for the code in their projects or on learning basis.
Today I am going to write a program on Printing Largest and Smallest among various numbers in Java . All those who are preparing for an interview
or want to enhance their coding skills in Java can go through the other JAVA PROGRAMS on this blog and you can also provide suggestions on
various other programs we can include in our Coding section in this blog in the comments below .

Now there are various of finding the Largest and Smallest number among various numbers in Java .One of the simplest way is to achieve this
through using Arrays . But the Limitation of using an Array for this purpose is that, we need to define a definite length of the array
and also the elements inside it. Since this is the foremost basic program that should be known to developers ,after this we'll also include
the enhanced versions of this program .

Below you can find the basic steps of the program .

1. Create an array with the definite size and elements predefined.
2. Assign first element of an array to two variables  named as largest and smallest.
3. Now using a FOR loop traverse the array .
4. If any  no. found in Array which is larger than the one assigned in variable named as largest the new no. will be assigned to variable largest.
5. If any  no. found in Array which is smaller than the one assigned in variable named as smallest the new no. will be assigned to variable smallest.
The loop will be executed  as many times as length of the array.
6. After the loop has ended ,Print both the numbers .

public class JavaInHouseLSExample{

        public static void main(String[] args) {
                int numbersArrayArray[] = new int[]{32,43,53,54,32,}; // (1)
                int smallest = numbersArray[0]; // (2)
                int largest = numbersArray[0]; // (2)
                for(int i=1; i< numbersArray.length; i++) //(3)
                        if(numbersArray[i] > largest)
                                largest = numbersArray[i]; //(4)
                        else if (numbersArray[i] < smallest)
                                smallest = numbersArray[i]; //(5)
                System.out.println("Largest Number is : " + largest); //(6)
                System.out.println("Smallest Number is : " + smallest);//(6)

if you have any questions or suggestions please comment below. 

Post a Comment