Wednesday, August 24, 2011

Find a largest and smallest element in array in Java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package largestandsmallest;
import java.io.*;
/**
 *
 * @author Gurpreet
 */
public class Largestandsmallest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
       DataInputStream in=new DataInputStream(System.in);
       int array[]=new int[5];
       int i,j;
       int temp;
       int choice;
       try
       {
           for(i=0;i<5;i++)
           {
                System.out.printf("a[%d]=",i);
                array[i]=Integer.parseInt(in.readLine());
               
           }
          
           j=1;
        while(j==1)
        {
           System.out.printf("\n Enter 1 for checking largest\n Enter 2 for checking smallest\n Enter Your Choice:");
           choice=Integer.parseInt(in.readLine());
           switch(choice)
           {
               case 1:
          
           temp=array[0];
           for(i=0;i<5;i++)
           {
              if(temp<array[i])
              {
                  temp=array[i];
              }
           }
           System.out.printf("\n Largest Element is=%d",temp);
                   break;
               case 2:
                  
           temp=array[0];
           for(i=0;i<5;i++)
           {
              if(temp>array[i])
              {
                  temp=array[i];
              }
           }
           System.out.printf("\n Smallest Element is=%d",temp);
                   break;
               default:
                   System.out.printf("\n\t\t***** INVALID CHOICE *****");
           }
        }
           }   catch(IOException e) {}
           
   
   
    }
}