Command Line Arguments are values passed to a program when it is executed from the command line. They allow users to provide input without using functions like scanf().
Syntax
int main(int argc, char *argv[])
or
int main(int argc, char **argv)
Explanation
- argc (Argument Count): Stores the total number of command-line arguments, including the program name.
- argv (Argument Vector): An array of strings containing the command-line arguments.
argv[0]→ Program nameargv[1]→ First argumentargv[2]→ Second argument, and so on.
Example Program
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
printf("Total Arguments = %d\n", argc);
for(i = 0; i < argc; i++)
{
printf("Argument %d = %s\n", i, argv[i]);
}
return 0;
}
Sample Execution
Compile:
gcc cmd.c -o cmd
Run:
./cmd Hello World 123
Output
Total Arguments = 4
Argument 0 = ./cmd
Argument 1 = Hello
Argument 2 = World
Argument 3 = 123
Example: Adding Two Numbers Using Command Line Arguments
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if(argc != 3)
{
printf("Usage: %s num1 num2\n", argv[0]);
return 1;
}
int a = atoi(argv[1]);
int b = atoi(argv[2]);
printf("Sum = %d\n", a + b);
return 0;
}
Sample Execution
./cmd 10 20
Output:
Sum = 30
Advantages
- Easy to pass input while running the program.
- Useful for automation and shell scripting.
- Eliminates the need for interactive input (
scanf).
Category: MCA
