Monday, September 6, 2021

Find Largest And Smallest Number in a Given Array Java Program

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

  1. Find Largest and Second Largest Number in Given Array Java Program
  2. How to Find Common Elements Between Two Arrays Java Program
  3. Find 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-

  1. Java Program to Find The Longest Palindrome in a Given String
  2. Find All Permutations of a Given String Java Program
  3. How to Convert Date to String in Java
  4. How to Read File From The Last Line in Java
  5. Creating Tar File And GZipping Multiple Files in Java
  6. How to Remove Elements From an ArrayList in Java
  7. Executor And ExecutorService in Java With Examples
  8. Java Reflection API Tutorial