Good Understanding of array data structure is very important for any software developer, and to develop this understanding there are lots of programming exercise beginners can do. One of them is writing

This problem is also known as

Btw, if you preparing for programming job interview, then don't forget to check the Cracking the Coding Interview book. It contains 150 Programming Questions and Solutions, which is more than enough for many coding interviews.

##

Here is full code example of Java program to find smallest and largest number from an integer array. You can create a Java source file with name MaximumMinimumArrayDemo.java and copy code there to compile and execute in your favorite IDE. If you don't have IDE setup, you can also compile and run this program by following steps I have shown on HelloWorld in Java.

If you look at the code here, we have created a method called largestAndSmallest(int[] numbers) to print largest and smallest number from int array passed to the program. We use two variables largest and smallest to store the maximum and minimum values from the array. Initially largest is initialized with Integer.MIN_VALUE and smallest is initialized with Integer.MAX_VALUE.

In each iteration of the loop, we compare current number with largest and smallest and update them accordingly. Since if a number is larger than largest, it can't be smaller than smallest, which means you don't need to check if the first condition is true, that's why we have used if-else code block, where else part will only execute if the first condition is not true.

Here is another logic to find the largest element from an array in Java, here instead of assigning the variable with Integer.MAX_VALUE, we have assigned the first element from the array.

Since array doesn't override the toString method in Java, we have used Arrays.toString() to print contents of an array. Remember this function is outside of core logic, so it's Ok to use it. Since this is a static method we can directly call this from the main method in Java, and so does our test code. We pass the random array to this method and see if largest and smallest number returned by the method is correct or not. For automated testing, a Unit test is better but for demonstration, you can use the main method.

That's all about

The Coding Interview Bootcamp: Algorithms + Data Structures

Data Structures and Algorithms: Deep Dive Using Java

Algorithms and Data Structures - Part 1 and 2

*a program to find smallest and largest number in an integer array*. Java programmers are no different than others, so they can do this program in Java, not just to understand array but also relational operators available in Java. In this program, you need to write a method, yes we call the function a method in Java, which will accept an integer array and then print largest and smallest number from that array. Use of any third-party library or API method is not allowed, which means you need to do this exercise by using basic tools of Java programming language, which includes operators, control statements, keyword and some classes from java.lang package.This problem is also known as

**finding maximum and minimum numbers in an array**, and technique mentioned here can be used in any other programming language as well. As a bonus point, you can also write JUnit test cases to test your method, I have not done so and relied on simple main method to test my code to show the output and keep it short, essential for any example or demo.Btw, if you preparing for programming job interview, then don't forget to check the Cracking the Coding Interview book. It contains 150 Programming Questions and Solutions, which is more than enough for many coding interviews.

##
__Java Program to find smallest and largest number in an integer array __

If you look at the code here, we have created a method called largestAndSmallest(int[] numbers) to print largest and smallest number from int array passed to the program. We use two variables largest and smallest to store the maximum and minimum values from the array. Initially largest is initialized with Integer.MIN_VALUE and smallest is initialized with Integer.MAX_VALUE.

In each iteration of the loop, we compare current number with largest and smallest and update them accordingly. Since if a number is larger than largest, it can't be smaller than smallest, which means you don't need to check if the first condition is true, that's why we have used if-else code block, where else part will only execute if the first condition is not true.

Here is another logic to find the largest element from an array in Java, here instead of assigning the variable with Integer.MAX_VALUE, we have assigned the first element from the array.

Since array doesn't override the toString method in Java, we have used Arrays.toString() to print contents of an array. Remember this function is outside of core logic, so it's Ok to use it. Since this is a static method we can directly call this from the main method in Java, and so does our test code. We pass the random array to this method and see if largest and smallest number returned by the method is correct or not. For automated testing, a Unit test is better but for demonstration, you can use the main method.

__Java Program to find the largest and smallest element in array:__import java.util.Arrays; /** * Java program to find largest and smallest number from an array in Java. * You cannot use any library method both from Java and third-party library. * * @author http://java67.blogspot.com */ public class MaximumMinimumArrayDemo{ public static void main(String args[]) { largestAndSmallest(new int[]{-20, 34, 21, -87, 92, Integer.MAX_VALUE}); largestAndSmallest(new int[]{10, Integer.MIN_VALUE, -2}); largestAndSmallest(new int[]{Integer.MAX_VALUE, 40, Integer.MAX_VALUE}); largestAndSmallest(new int[]{1, -1, 0}); } public static void largestAndSmallest(int[] numbers) { int largest = Integer.MIN_VALUE; int smallest = Integer.MAX_VALUE; for (int number : numbers) { if (number > largest) { largest = number; } else if (number < smallest) { smallest = number; } } System.out.println("Given integer array : " + Arrays.toString(numbers)); System.out.println("Largest number in array is : " + largest); System.out.println("Smallest number in array is : " + smallest); } } Output: Given integer array : [-20, 34, 21, -87, 92, 2147483647] Largest number in array is : 2147483647 Smallest number in array is : -87 Given integer array : [10, -2147483648, -2] Largest number in array is : 10 Smallest number in array is : -2147483648 Given integer array : [2147483647, 40, 2147483647] Largest number in array is : 2147483647 Smallest number in array is : 40 Given integer array : [1, -1, 0] Largest number in array is : 1 Smallest number in array is : -1

That's all about

**How to find largest and smallest number from integer array in Java**. As I said this question can also be asked as to find the maximum and minimum numbers in an Array in Java, so don't get confused there. By the way, there are more ways to do the same task and you can practice it to code solution differently. Can you write a solution which is different than this? go ahead and give it a try.

**Further Learning**

The Coding Interview Bootcamp: Algorithms + Data Structures

Data Structures and Algorithms: Deep Dive Using Java

Algorithms and Data Structures - Part 1 and 2

__Some more programs for coding interviews:__- How to check if a given number is prime or not? (solution)
- How to find the highest occurring word from a text file in Java? (solution)
- How to find if given String is palindrome in Java? (solution)
- How to reverse an int variable in Java? (solution)
- How do you swap two integers without using the temporary variable? (solution)
- Write a program to check if a number is a power of two or not? (solution)
- How to reverse String in Java without using StringBuffer? (solution)
- How do you reverse word of a sentence in Java? (solution)
- How to find a missing number in a sorted array? (solution)
- How to find the square root of a number in Java? (solution)
- How to calculate GCD of two numbers in Java? (solution)
- How to find duplicate characters from a given String? (solution)

hard???

ReplyDeleteThis code doesn't look right, it should be changed to (remove "else"):

ReplyDeleteif (number > largest) {

largest = number;

}

if (number < smallest) {

smallest = number;

}

If you try {1, 2, 3}, you will see the difference.

Agreed. I ran the code example and encountered the incorrect result. It should be updated to have two separate if statements just as shown above.

DeleteWhy not just set largest/smallest to array[0] instead of INT_MAX, INT_MIN? Then it'll work with the `else`. Setting to INT_MAX/INT_MIN is a rather rookie mistake.

DeleteRemove "else" because it fails at both places.

ReplyDelete1. for largest try ascending order digit (1,2,3)

2. for smallest try descending order digit in negative(-3,-2,-1)

Yes, the else looks like a typo, it should be removed otherwise solution will not produce correct result for all outputs.

Delete//programm to find largest no in an given array.

ReplyDeletepublic class Larg {

public static void main(String[] args) {

int max=0;

int arr[]={900,2,54,15,40,100,20,011,299,30,499,699,66,77};

max=arr[0];

for(int i=0;i<arr.length-1;i++)

{

if(max<arr[i+1])

{

max=arr[i+1];

}

}

System.out.println(max);

}

}

nice article

ReplyDeleteCan we convert into array into string without API or without Arrays.to String(arr)

ReplyDeleteCan we convert int array to string without using Arrays.to string()

ReplyDeleteprivate static void largestAndSmallest(int[] numbers) {

ReplyDeleteint largest = numbers[0];

int smallest = numbers[0];

for (int i = 1; i < numbers.length; i++) {

if(numbers[i]>largest){

largest=numbers[i];

}else if(numbers[i]<smallest){

smallest=numbers[i];

}

}

System.out.println("\nGiven integer array : " + Arrays.toString(numbers));

System.out.println("Largest number in array is : " + largest);

System.out.println("Smallest number in array is : " + smallest);

}

ReplyDeleteimport java.util.Scanner;

class exam

{

public static void main(String[] args)

{

Scanner input = new Scanner(System.in);

System.out.println("Enter 5 numbers:");

int[] numbers = new int[5];

int sum = 0;

int max = numbers[0];

int min = numbers[0];

for(int i=0; i<5; i++){

numbers[i] = input.nextInt();

sum = sum + numbers[i];

if (numbers[i] > max){

max = numbers[i];

}

else if (numbers[i] < min){

min = numbers[i];

}

}

int average = sum / 5;

System.out.println("Sum: " + sum);

System.out.println("Average: " + average);

System.out.println("Max: " + max);

System.out.println("Min: " + min );

System.out.println("Display sorted data : " + numbers[0] );

}

}

How come the min is always displaying 0...Please can someone help me...Thanks in advance

Else in this snippet "else if (numbers[i] < min){" is the culprit

Deletepublic void doAlgorithm(int a[]){

ReplyDeleteint big = 0, temp = 0;

for (int i = 0; i < a.length; i++) {

for (int j = i+1; j < a.length; j++) {

big = (a[i] > a[j]) ? a[i] : a[j];

if(temp < big)

temp = big;

}

}

System.out.println(temp);

}

laughable

ReplyDeletewhy all this hassle with Integer.MAX_VALUE and Integer.MIN_VALUE?

Simply make your largest and smallest values equal to the numbers[0]. Then you can save one iteration.

What if the numbers is empty? You will still get Integer.MIN_VALUE and Integer.MAX_VALUE which obviously would be incorrect. You need to check for empty and null array.

A programmer should learn to check his inputs way earlier, than he would learn algorithms. It's a matter of simple hygiene - learn to brush your teeth before learning how to assemble fusion reactor.

int[] arr = {1,3,2,6,3};

ReplyDeleteArrays.sort(arr);

int min = arr[0];

int max = arr[arr.length-1];

System.out.println(min + ":" + max);

Here is the code

ReplyDeleteWhy not you correct code in this post..please replace else if with if condition..

ReplyDeleteint a[]= {10,3,0,1,45,22,667,8,99,0,3};

ReplyDeleteint min = a[0];

int max = a[1];

int minPos = 0;

int maxPos = 1;

if(maxa[i]) {

min = a[i];

minPos = i;

}

if(max<a[i]) {

max = a[i];

maxPos = i;

}

}

System.out.println("min : "+ min +" Pos : "+(minPos+1));

System.out.println("max : "+ max +" Pos : "+(maxPos+1));

import java.util.Arrays;

ReplyDeleteimport java.util.Collections;

import java.util.List;

import org.apache.commons.lang3.ArrayUtils;

public class Test{

int []arr = {-1 , 3,2, -9, 5 ,6 ,-4};

System.out.println("Largest is "+findLargest(arr));

System.out.println("Smallest is "+findSmallest(arr));

}

private static int findSmallest(int[] arr) {

List b = Arrays.asList(ArrayUtils.toObject(arr));

return (int) Collections.min(b);

}

public static int findLargest(int [] arr){

List b = Arrays.asList(ArrayUtils.toObject(arr));

return (int) Collections.max(b);

}

}

public static void main (String []args){

ReplyDeletelargestAndSmallest(new Integer[]{-20, 34, 21, -87, 92,

10,100,-120});

}

public static void largestAndSmallest(Integer[] numbers)

{

int largest = 0;

int smallest = 0;

int temp = 0;

/*

//// simple using builtin function for sorting array in ascending order ////

Arrays.sort(numbers);

System.out.println("In asscending order : " + Arrays.toString(numbers));

//// simple using builtin function for sorting array in descending order ////

Arrays.sort(numbers, Collections.reverseOrder());

System.out.println("In descending order : " + Arrays.toString(numbers));

*/

for(int i=0; i numbers[j]){

// temp = numbers[i];

// numbers[i]=numbers[j];

// numbers[j]=temp;

// }

// largest = numbers[0];

// smallest = numbers[j];

}

}

System.out.println("Given integer array : " + Arrays.toString(numbers));

System.out.println("Largest number in array is : " + largest);

System.out.println("Smallest number in array is : " + smallest);

}