binibiningtinamoran

MaxAndMin

Oct 29th, 2019
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.24 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4. public class MaxAndMin {
  5.  
  6.     public static void main(String []args) {
  7.         Scanner scan = new Scanner(System.in);
  8.  
  9.         System.out.print("Enter the size of the array: ");
  10.         int sizeOfArray = scan.nextInt();
  11.  
  12.         while (sizeOfArray <= 0) {
  13.             System.out.println("Size input is invalid.");
  14.             System.out.print("Enter the size of the array: ");
  15.             sizeOfArray = scan.nextInt();
  16.         }
  17.  
  18.         int[] theArray = new int[sizeOfArray];
  19.  
  20.         for (int i = 0; i < theArray.length; i++) {
  21.             System.out.print("Enter integer to be added to array: ");
  22.             theArray[i] = scan.nextInt();
  23.         }
  24.  
  25.         System.out.printf("\nThe largest number in the array is %,d\n", findMax(theArray));
  26.         System.out.printf("The index of largest number in the array is %,d\n",
  27.                 indexOfMax(theArray));
  28.         System.out.printf("The smallest number in the array is %,d\n", findMin(theArray));
  29.         System.out.printf("The index of smallest number in the array is %,d", indexOfMin(theArray));
  30.     }
  31.  
  32.     public static int findMax(int[] someArray) {
  33.  
  34.         int largestInArray = someArray[0];
  35.         for (int element : someArray) {
  36.             if (largestInArray < element) {
  37.                 largestInArray = element;
  38.             }
  39.         }
  40.         return largestInArray;
  41.     } // end findMax()
  42.  
  43.     public static int indexOfMax(int[] someArray) {
  44.  
  45.         int pos = 0;
  46.         for (int i = 0; i < someArray.length; i++) {
  47.             pos = someArray[i] > someArray[pos] ? i : pos;
  48.         }
  49.         return pos;
  50.     } // end indexOfMax()
  51.  
  52.     public static int findMin(int[] someArray) {
  53.  
  54.         int smallestInArray = someArray[0];
  55.         for (int element : someArray) {
  56.             if (smallestInArray > element) {
  57.                 smallestInArray = element;
  58.             }
  59.         }
  60.         return smallestInArray;
  61.     } // end findMin()
  62.  
  63.     public static int indexOfMin(int[] someArray) {
  64.  
  65.         int pos = 0;
  66.         for (int i = 0; i < someArray.length; i++) {
  67.             pos = someArray[i] < someArray[pos] ? i : pos;
  68.         }
  69.         return pos;
  70.     } // end indexOfMin()
  71.  
  72.  
  73.  
  74. } // end class
Advertisement
Add Comment
Please, Sign In to add comment