Showing posts with label finding minimum. Show all posts
Showing posts with label finding minimum. Show all posts

Thursday, 14 October 2021

Java program to find the maximum and minimum number in an array given as command line argument

 Given an array of numbers as input, this Java program finds the maximum number in the array using a linear search approach. Through this program, we can learn how to pass arrays as an argument to a function.

PROGRAM

class MinMax

{

   static int findMin(int[] a)

   {

      int min=a[0];

       for(int i=0;i<a.length;i++)

       {

         if (a[i]<min)

           min=a[i];

        }

        return min;

    }

   static int findMax(int[] a)

   {

      int max=a[0];

       for(int i=0;i<a.length;i++)

       {

         if (a[i]>max)

           max=a[i];

        }

        return max;

    }

    public static void main(String[] arg)

    {

      int n=arg.length;

      int[] num=new int[n];

      for(int i=0;i<n;i++)

       num[i]=Integer.parseInt(arg[i]);

      System.out.println("The original array");

      for(int i=0;i<num.length;i++)

      System.out.println(num[i]+"\t");

      System.out.println("The smallest number in the array = "+findMin(num));

      System.out.println("The largest number in the array = "+findMax(num));

    }

}


OUTPUT

E:\Java\Programs>java MinMax 3 4 6 2 9 1 -4 8

The original array

3

4

6

2

9

1

-4

8

The smallest number in the array = -4

The largest number in the array = 9