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;

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
 * @param num
 * @return
public void minMaxNumber(int[] num) {
	System.out.println("Input Array: "+Arrays.toString(num));
	int min,max;
	for(int i=0;i<num.length;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 FacebookTwitterTumblr.


Popular posts from this blog

Calculate Your CTC Salary Hike Percentage - Online Calculator to find your New Salary

Find the Longest Streak of 1's in a Binary Array using Java Code

Java Program to read Excel File and Load into Array

Java Program to Read a Properties file and return a Property Value

Create a File logging Utility using Java Code