Command Line Argument in C Programming

In C programming often a situation may come where we want to pass the information into a program during the execution of the program. These values are called Command Line Arguments(CLA).

The “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 that 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 to take one value from user during execution as a Command Line Argument in C Language

Note: Suppose the 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 the 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

Program 2: Write A Program to Add two numbers using Command Line Argument in C Programming

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 the circle and take the area input from the command line argument

gcc circle.c ./circle 5

Output
Area of circle = 78.50

Read More

  1. C++ program for student details
  2. Anonymous Object in C++
  3. Lowercase character to uppercase character
  4. Local vs Global Object in C++
  5. Local and Nested Classes in C++
  6. Arithmetic operations using switch case
  7. Switch Case in C Programming
  8. Constructor in C++
  9. Know more about C++