Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 885

Find Largest and Smallest Number in the Given Array - Java Program

$
0
0

This post is about writing a Java program to find the largest and the smallest number in the given array or it can also be rephrased as - Find the maximum and minimum number in the 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

Logic here is to have two variables for maximum and minimum number, 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 the Given Array - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Find Largest and Second Largest Number in Given Array - Java Program
  2. How to Find Common Elements Between Two Arrays - Java Program
  3. Finding duplicate elements in an array - Java Program
  4. How to remove elements from an array - Java Program
  5. Matrix Multiplication Java Program

You may also like -

>>>Go to Java Programs page


Viewing all articles
Browse latest Browse all 885

Trending Articles