Advertisement
Shailrshah

Smallest Even and Largest odd numbers in an Array

Aug 20th, 2013
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1. import java.io.*;
  2. class Arrays{
  3.     private static String getInput(String prompt){
  4.         BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
  5.         System.out.print(prompt);
  6.         System.out.flush();
  7.         try{
  8.             return stdin.readLine();
  9.         }catch(Exception e){
  10.             return "Error: " + e.getMessage();
  11.         }
  12.     }
  13.     public static void main(String args[]) {
  14.         String input = getInput("Enter the number of elements: ");
  15.         int n = Integer.parseInt(input);
  16.         int [] a = new int [n];
  17.         int [] even = new int [n];
  18.         int [] odd = new int [n];
  19.         int i, countEven = 0, countOdd = 0;
  20.         for(i = 0; i<n; i++){
  21.             input = getInput("Enter an element: ");
  22.             a[i] = Integer.parseInt(input);
  23.             if (a[i]%2 == 0)
  24.                 even[countEven++] = a[i];
  25.             else
  26.                 odd[countOdd++] = a[i];
  27.         }
  28.         int smallEven = even [0];
  29.         for(i = 0; i<countEven; i++){
  30.             System.out.print(even[i] + " ");
  31.             if(even[i] < smallEven)
  32.                 smallEven = even[i];
  33.         }
  34.         System.out.println(" are even. The smallest out of the "+countEven+" is "+smallEven);
  35.         int largeOdd = odd[0];
  36.         for(i = 0; i<countOdd; i++){
  37.             System.out.print(odd[i] + " ");
  38.             if(odd[i] > largeOdd)
  39.                 largeOdd = odd[i];
  40.         }  
  41.         System.out.println("are odd. The largest out of the "+countOdd+" is "+largeOdd);
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement