Command-line Arguments in C

Command-line arguments allow us to pass input values to a C program directly from the terminal when running the executable. This makes programs more flexible, interactive, and automated.

What Are Command-line Arguments?

When we run a C program using a terminal command like:

./a.out Hello 123

The values Hello and 123 are passed to the program using:

Syntax of main() with Command-line Arguments

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

How Arguments Are Stored?

Command:  ./myprog Apple Mango 100

argc = 4

argv[0] = "./myprog"
argv[1] = "Apple"
argv[2] = "Mango"
argv[3] = "100"

Practical Example 1 – Print All Arguments

#include <stdio.h>

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

    printf("Total arguments: %d\n", argc);

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

    return 0;
}

Practical Example 2 – Add Two Numbers

#include <stdio.h>
#include <stdlib.h>

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

    if(argc != 3){
        printf("Usage: ./a.out num1 num2");
        return 0;
    }

    int a = atoi(argv[1]);
    int b = atoi(argv[2]);

    printf("Sum = %d", a + b);

    return 0;
}

Practical Example 3 – Check Username

#include <stdio.h>
#include <string.h>

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

    if(argc != 2){
        printf("Provide username");
        return 0;
    }

    if(strcmp(argv[1], "admin") == 0)
        printf("Access Granted");
    else
        printf("Access Denied");

    return 0;
}

Practical Example 4 – Count Length of Argument

#include <stdio.h>
#include <string.h>

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

    if(argc < 2){
        printf("Enter text");
        return 0;
    }

    printf("Length = %lu", strlen(argv[1]));

    return 0;
}

Practical Example 5 – Multiply N Numbers

#include <stdio.h>
#include <stdlib.h>

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

    int product = 1;

    for(int i = 1; i < argc; i++)
        product *= atoi(argv[i]);

    printf("Product = %d", product);

    return 0;
}

Uses of Command-line Arguments

Practice Questions

  1. What is argc and argv?
  2. Why is argv[0] special?
  3. Write a program to print last argument.
  4. Write a program to convert argv input to uppercase.
  5. Create a calculator using command-line arguments.

Practice Task

Write a program using command-line arguments to display: ✔ Total words ✔ Longest word ✔ Shortest word ✔ Word containing maximum vowels