Friday, July 1, 2022

Find Largest and Second Largest Number in Given Array Java Program

This post is about writing a Java program to find the top two numbers (largest and second largest) in a given array.

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

Solution to find largest and second largest number in an array

Logic here is to have two variables for first and second number and iterate the array. Compare each array element with the first number if first number is less than the array element then assign existing first number to second number and array element to the first number.

If first number is greater than the array element then check if second element is less than the array element, if yes then assign array element to the second number.

Largest and second largest number in array Java program

public class FindTopTwo {

 public static void main(String[] args) {
  int numArr[] = {2, 5, 14, 1, 26, 65, 123, 6};
  // Assign lowest possible int value
  int firstNum = Integer.MIN_VALUE;
  int secondNum = Integer.MIN_VALUE;
  
  for(int i = 0; i < numArr.length; i++){
   if(firstNum < numArr[i]){
    secondNum = firstNum;
    firstNum = numArr[i];
   }else if(secondNum < numArr[i]){
    secondNum = numArr[i];
   } 
  }
  System.out.println("Top two numbers : First -  " 
     + firstNum + " Second " + secondNum);
 }
}

Output

Top two numbers : First -  123 Second 65

That's all for this topic Find Largest and Second Largest Number in 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. How to Remove Elements From an Array Java Program
  2. Matrix Addition Java Program
  3. How to Find Common Elements Between Two Arrays Java Program
  4. Arrange Non-Negative Integers to Form Largest Number - Java Program
  5. Remove Duplicate Elements From an Array in Java

You may also like-

  1. Count Number of Times Each Character Appears in a String Java Program
  2. Invoking Getters And Setters Using Reflection in Java
  3. How to Convert Date And Time Between Different Time-Zones in Java
  4. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  5. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  6. How to Create Immutable Class in Java
  7. BigDecimal in Java With Examples
  8. Interface Default Methods in Java