Command-Line Arguments in C Programming (Complete Guide with Examples)


This tutorial explains command-line arguments in C, which allow users to pass information to a program when it is executed. It covers argc, argv, and practical examples to make programs flexible and interactive.

1. What are Command-Line Arguments

  1. Command-line arguments allow passing inputs to a C program while running it from the terminal.
  2. Useful when you want programs to accept parameters dynamically instead of using scanf().
  3. Two parameters are used in main() to handle command-line arguments:

int main(int argc, char *argv[])
ParameterDescription
argcArgument count – number of arguments passed including program name
argvArgument vector – array of strings containing the arguments

2. Example: Display Command-Line Arguments


#include <stdio.h>

int main(int argc, char *argv[]) {
printf("Number of arguments: %d\n", argc);

for(int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}

return 0;
}

Example Run:


$ ./program Muni 25 Mumbai
Number of arguments: 4
Argument 0: ./program
Argument 1: Muni
Argument 2: 25
Argument 3: Mumbai

Explanation:

  1. argv[0] always contains the program name
  2. Subsequent elements (argv[1] onward) contain user-provided arguments

3. Example: Sum of Two Numbers Using Command-Line Arguments


#include <stdio.h>
#include <stdlib.h> // for atoi()

int main(int argc, char *argv[]) {
if(argc != 3) {
printf("Usage: %s num1 num2\n", argv[0]);
return 1;
}

int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);
int sum = num1 + num2;

printf("Sum = %d\n", sum);
return 0;
}

Example Run:


$ ./program 10 20
Sum = 30

Explanation:

  1. atoi() converts string to integer
  2. Command-line arguments allow program to be flexible and reusable

4. Key Points to Remember

  1. argc counts all arguments, including program name
  2. argv is an array of *strings (char )
  3. Use atoi() or atof() to convert arguments to numbers
  4. Useful for scripts, automation, and dynamic input programs