Given an array {7, 5, 8, 3, 1, 4} – write a program that will return the largest 3 nos

public class ReturnThreeMaxNos {

 public static void main(String[] args)
 {
  int array[] = {
    1, 22, 1, 3, 212, 4, 43, 5, 1
  };
  
  int max = -1;
  int max2 = -1;
  int max3 = -1;
  
  for (int i : array) {
   if (i > max) {
    max3  = max2;
    max2 = max;
    max = i;
   }
   else if (i > max2) {
    max3 = max2;
    max2 = i;
   }
   else if (i > max3) {
    max3 = i;
   }
  }
  
  Formatter f = new Formatter();
  f.format("The max is: %d\n The 2nd max is: %d\n the 3rd max is: %d", max, max2, max3);
  System.out.print(f.toString());
  
 }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

     

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">