binibiningtinamoran

FindMaxAndMinInArray

Nov 7th, 2019
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4. public class FindMaxAndMinInArray {
  5.  
  6.     public static void main(String[] args) {
  7.  
  8.         Scanner scan = new Scanner(System.in);
  9.  
  10.         System.out.print("Enter size of the array: ");
  11.         int sizeOfArray = Integer.parseInt(scan.nextLine());
  12.  
  13.         // Validate input. Size of array cannot be negative or equal to 0!
  14.         while (sizeOfArray <= 0) {
  15.             System.out.println("Size must be greater than 0!");
  16.             System.out.print("Enter size of the array: ");
  17.             sizeOfArray = Integer.parseInt(scan.nextLine());
  18.         }
  19.  
  20.         // Initialize array with size!
  21.         int[] numArray = new int[sizeOfArray];
  22.  
  23.         int sum = 0;
  24.  
  25.         for (int i = 0; i < numArray.length; i++) {
  26.             System.out.printf("Enter integer # %,d: ", i+1);
  27.             // Store number entered into array
  28.             numArray[i]= Integer.parseInt(scan.nextLine());
  29.             sum += numArray[i]; // add numbers entered
  30.         }
  31.         System.out.println("\nSUM: " + sum);
  32.         System.out.printf("AVERAGE: %,.2f\n", ((double)sum / numArray.length));
  33.  
  34.         // Without using if-else, just sort the Array from smallest to largest
  35.         // to find max and min
  36.         Arrays.sort(numArray);
  37.         System.out.println("MAX: " + (numArray[numArray.length-1]));
  38.         System.out.println("MIN: " + (numArray[0]));
  39.  
  40.         // Using if-else to find max and min
  41.         int largestInArray= numArray[0];
  42.         int smallestInArray = numArray[0];
  43.  
  44.         for (int element : numArray) {
  45.             if (largestInArray < element) {
  46.                 largestInArray = element;
  47.             }
  48.             if (smallestInArray > element) {
  49.                 smallestInArray = element;
  50.             }
  51.         }
  52.  
  53.         System.out.println("\nMAX: " + largestInArray);
  54.         System.out.println("MIN: " + smallestInArray);
  55.  
  56.  
  57.  
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment