Showing posts with label command line arguments. Show all posts
Showing posts with label command line arguments. 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


Friday 18 June 2021

Shell script to work with command line arguments

In this shell script, we will learn the use of the commands to display the first command-line argument and the total number of command-line arguments in a shell script.

$0 - always refers to the shell program being executed

$# - returns the total number of arguments given in the command line

$@ - returns the entire list of the arguments in the command line

$* - returns the entire list of arguments in the command line double quoted

$1, $2,.............., $9 -  returns the arguments in the position specified


PROGRAM

#Shell script to work with command line arguments
echo -e "\nThe first argument in a command line refers to the program name"
echo -e "The first argument here is $0 \n"
echo "The list of arguments given in the command line are"
echo -e "$* \n"
echo "The total number of command line arguments is " : $#



OUTPUT

$ sh clarg.sh hello welcome to unix programming


The first argument in a command line refers to the program name

The first argument here is clarg.sh


The list of arguments given in the command line are

hello welcome to unix programming


The total number of command line arguments is  : 5