• Hi Friends today we will discuss about how to find top two maximum numbers in an array using java program.
  • For this we have written separate function to perform logic
  • findTwoMaxNumbers method takes integer  array as an argument
  • Initially take two variables to find top to numbers and assign to zero.
  • By using for each loop iterating array and compare current value with these values
  • If our value is less than current array value then assign current value to max1 
  • And assign maxone to maxtwo because maxtwo should be second highest.
  • After completion of all iterations maxone will have top value and maxtwo will have second maximum value.
  • Print first maximum and second maximum values.
  • So from main method create array and pass to findTwoMaxNumbers(int [] ar).


Program #1: Java interview programs to practice: find top two maximum numbers in an array without recursion 

  1. package arraysInterviewPrograms.instanceofjava;
  2. public class FindTopTwo {
  3.  
  4. public void findTwoMaxNumbers(int[] array){
  5.        
  6.  int maxOne = 0;
  7.  int maxTwo = 0;
  8.  
  9. for(int i:array){
  10.  
  11.     if(maxOne < i){
  12.            maxTwo = maxOne;
  13.            maxOne =i;
  14.      } else if(maxTwo < i){
  15.                 maxTwo = i;
  16.      }
  17. }
  18.         
  19.  
  20.   System.out.println("First Maximum Number: "+maxOne);
  21.   System.out.println("Second Maximum Number: "+maxTwo);
  22. }
  23.      
  24. public static void main(String a[]){
  25.  
  26.         int num[] = {4,23,67,1,76,1,98,13};
  27.         FindTopTwo obj = new FindTopTwo();
  28.         obj.findTwoMaxNumbers(num);
  29.         obj.findTwoMaxNumbers(new int[]{4,5,6,90,1});
  30.  
  31. }
  32.  
  33. }


Output:


  1. First Maximum Number: 98
  2. Second Maximum Number: 76
  3. First Maximum Number: 90
  4. Second Maximum Number: 6

Program #2:Java program to find top two maximum numbers in an array using eclipse IDE

top two maximum number in array java


Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu