### Java Program to Find the Smallest and Largest number in an Array of Integers

Array operations on int arrays is a common Interview Question in Java. Finding the minimum number or the maximum number (smallest or largest number) in an array requires traversing the whole array and giving the output.

We'll try to solve both problems in this post. You can go through the logic and utilize it as per your requirement.

The logic is simple, we'll go through each element in a array, and compare it to a minimum or maximum number.

We've initialized the minimum/maximum number as the first element of the array.

int min,max; min=max=num[0];

Now, if the next element in the array is lesser/greater than the stored minimum/maximum number then we'll change the mimimum/maximum number to match it.

Once we're done with the whole array, we get the minimum/maximum number of the array.

Below is the complete code for reference:

/** * Find the Largest and Smallest number in a Array of Integers * @author computengine.com * @param num * @return */ public void minMaxNumber(int[] num) { System.out.println("Input Array: "+Arrays.toString(num)); int min,max; min=max=num[0]; for(int i=0;i<num.length;i++) { if(num[i]>max) max=num[i]; if(num[i]<min) min=num[i]; } System.out.println("Minimum: "+min); System.out.println("Maximum: "+max); }

Here is the output when the code is run. We're passing an int[] to it.

*Input Array: [2, 4, 5, 6, 3, 2, 4, 5, 566, 3, 22, 45, 1, 34, 3, 2]*

*Minimum: 1*

*Maximum: 566*

Thanks for Reading the Article. If you have reached this far, we hope that the article was useful to you! Please Like/Share/Follow us on Facebook, Twitter, Tumblr.

## Comments

## Post a Comment