This post is about writing a Java program to find the largest and the smallest number in a given
__array__ or it can also be rephrased as- Find the maximum and minimum number in a given array.

Condition here is that you should not be using any inbuilt Java classes (i.e. Arrays.sort) or any data structure.

### Solution to find the largest and the smallest number in an array

Logic here is to have two variables for maximum and minimum numbers, initially assign the element at the first index of the array to both the variables.

Then 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 check if minimum number is greater than the array element, if yes then assign array element to the minimum number.

### Java code

public class FindMaxMin { public static void main(String[] args) { int numArr[] = {56, 36, 48, 49, 29, 458, 56, 4, 7}; // start by assigning the first array element // to both the variables int maxNum = numArr[0]; int minNum = numArr[0]; // start with next index (i.e. i = 1) for(int i = 1; i < numArr.length; i++){ if(maxNum < numArr[i]){ maxNum = numArr[i]; }else if(minNum > numArr[i]){ minNum = numArr[i]; } } System.out.println("Largest number - " + maxNum + " Smallest number - " + minNum); } }

__Output__

Largest number - 458 Smallest number - 4

That's all for this topic **Find Largest And Smallest Number in a Given Array Java Program**. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page

__Related Topics__

**You may also like- **