Home » Posts tagged 'command-line-argument'

Tag Archives: command-line-argument

Command Line Argument in C Programming

In a C programming often a situation may come where we want to pass the information into a program during the execution of program.

These values are called Command Line Arguments(CLA).

“main()” function handles the command line argument.

Syntax:

int main( int argc, char *argv[] )
{

}

Here, argc refers to the number of arguments passed  and argv[] is a pointer array which points to each argument .

Note:

argc – argument count in command line argv[0]– holds the name of the program
argv[1]– holds the first command line argument,
argv[2]– holds the second command line argument and and so on.
If no argument is supplied, argc will be 1

          

Program1: Write a program in a C to take one value from user during execution as a command line argument.

Note: Suppose above program name is “CLA”.

Run this program as follows in Linux:

./CLA hello

Here hello is a command line argument.

Run this program as follows in Windows from command line:

program.exe  hello

 Here hello is a command line argument.

Output
No of command line arguments are 2
Program name is: CLA
Command line argument is: hello

Program2 : A C program to add two numbers using command line angument.

to convert string to integer atoi() method is used. Similar to convert string to float atof() is used

Compiling and running above program

gcc add.c ./a.out 5 6

Output
sum is 11
Program3: Write a program in a C to take 4 names input from command line argument and print it. Note: Suppose above program name is “names.c”.

gcc names.c ./names RAM MOHAN SOHAN RAMESH

Output
Program name : names
1st arg : RAM
2nd arg : MOHAN
3rd arg : SOHAN
4th arg : RAMESH

Program4: Find the radius of circle take area input from command line argument



gcc circle.c ./circle 5

Output
Area of circle = 78.50



Please follow and like us:
error