10 Dec 2017

write a program in java to find maximum and minimum value from an Array.


Method #1



import java.util.Scanner;
class ArrayMaxMin
{
          public static void main(String[] args)
          {
                   Scanner sc=new Scanner(System.in);
                   System.out.println("Enetr number of Array element want");
                   int n=sc.nextInt();
                   Integer[] arr=new Integer[n];
                   System.out.println("Eneter "+n+" integer elements for sequence ");
                   for(int i=0;i<n;i++)
                   {
                             arr[i]=sc.nextInt();
                   }
                   int max=arr[0];
                   int min=arr[0];
                   for(int i=0;i<arr.length;i++)
                   {
                             max=arr[i]>max?arr[i]:max;
                             min=arr[i]<min?arr[i]:min;
                   }
                   System.out.println("Maximum Number of Array "+max);
                   System.out.println("Minimum Number of Array "+min);
          }
}

Method #2

import java.util.Scanner;
import java.util.Arrays;
class ArrayMaxMin
{
          public static void main(String[] args)
          {
                   Scanner sc=new Scanner(System.in);
                   System.out.println("Enetr number of Array element want");
                   int n=sc.nextInt();
                   Integer[] arr=new Integer[n];
                   System.out.println("Eneter "+n+" integer elements for sequence ");
                   for(int i=0;i<n;i++)
                   {
                             arr[i]=sc.nextInt();
                   }
                   Arrays.sort(arr);
                   System.out.println("Maximum Number of Array "+arr[arr.length-1]);
                   System.out.println("Minimum Number of Array "+arr[0]);
          }
}

Output:



Method #3


import java.util.Arrays;
import java.util.Collections;
public class ArrayMaxMin {
public static void main(String[] args)
    {

        // Initializing array of integers
        Integer[] num = { 10,20,30,40,50 };

        // using Collection.min() to find minimum element
        // using only 1 line.
        int min = Collections.min(Arrays.asList(num));

        // using Collection.min() to find maximum element
        // using only 1 line.
        int max = Collections.max(Arrays.asList(num));

        // printing minimum and maximum numbers
        System.out.println("Maximum number of array  " + max);
        System.out.println("Minimum number of array   " + min);

    }
}

Output: