💻 18. Command Line Arguments

18.1 What Are Command Line Arguments?

Command line arguments are values supplied to a C program when the program starts. They let the program receive input from the command that launches it, instead of asking for that input later with scanf().

Command / Terminal
↓
Program + Arguments
↓
main(argc, argv)
↓
Validate → Convert → Process → Output
program.exe 10 20 30

Here 10, 20, and 30 are supplied to the program as command line arguments.

18.2 The main() Function

int main(int argc, char *argv[])
{
    return 0;
}

argc

argc counts the available argument strings. In a normal terminal launch it includes the program-name entry, so two user arguments normally give argc == 3.

argv

argv provides pointers to the argument strings. Valid argument strings occupy indexes below argc, and argv[argc] is a null pointer marking the end.

18.3 Understanding argc

Suppose the program is started as:

program.exe 10 20

Conceptually:

argc = 3 argv[0] → "program.exe" argv[1] → "10" argv[2] → "20" argv[3] → NULL

For a normal terminal launch, the program-name string is at argv[0]. Therefore, two user-supplied values normally make argc == 3.

18.4 Understanding argv

Think of argv as a table of strings:

argv │ ├── argv[0] → program name ├── argv[1] → first argument ├── argv[2] → second argument ├── argv[3] → third argument └── ...

argv[i] points to character text. The characters "25" must be converted before they can be used as the integer 25 in a numeric calculation.

18.5 Displaying Command Line Arguments

#include <stdio.h>

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

    return 0;
}

For program.exe apple 25, the program can display the arguments in order. The loop is safe because it stays within 0 ... argc - 1.

18.6 The Most Important Rule: Arguments Are Strings

Remember: argv[1] containing "25" is a string representing the characters 2 and 5. It is not an int with value 25.

So this is wrong when numeric arithmetic is required:

int sum = argv[1] + argv[2];

Convert the text, check whether conversion succeeded, and then calculate. Checking the argument count alone does not validate the contents.

18.7 Converting an Argument with atoi()

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

int main(int argc, char *argv[])
{
    if (argc != 3)
        return 1;

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

    printf("%d\n", a + b);
    return 0;
}

atoi() is used in the short calculation examples only with valid, in-range numeric arguments. It cannot distinguish a valid zero from many invalid inputs and does not provide reliable range checks. When validating input, prefer strtol().

18.8 strtol() — Safer Integer Conversion

#include <errno.h>
#include <limits.h>
#include <stdlib.h>

char *end;
errno = 0;
long value = strtol(argv[1], &end, 10);

if (errno == ERANGE || end == argv[1] || *end != '\0')
{
    /* invalid or out-of-range integer */
}

The useful idea is not merely conversion; it is validation. strtol() reports where conversion stopped through an end pointer. Check that at least one digit was read, no unwanted characters remain, and no range error occurred.

18.9 Adding Two Command Line Numbers

For a program started as program.exe 10 20:

int a = atoi(argv[1]);
int b = atoi(argv[2]);
printf("Sum = %d\n", a + b);

Before accessing argv[1] and argv[2], verify that the required arguments exist.

18.10 Subtraction, Multiplication and Division

Subtraction

a - b

Multiplication

a * b

Division

a / b

Check that b != 0 before integer division.

18.11 Processing Multiple Numeric Arguments

Once each argument has been converted, normal C algorithms can process them.

long sum = 0;
for (int i = 1; i < argc; i++)
    sum += strtol(argv[i], NULL, 10);

The sum or search algorithm is the same as with keyboard input. Only the way the initial values reach the program changes. Validate the argument strings before passing their converted values into that algorithm.

18.12 Finding Maximum and Minimum

First check that at least one data argument exists. Initialize both results from that value, then compare the remaining values. Starting maximum at zero would fail for an all-negative list.

long max = strtol(argv[1], NULL, 10);

for (int i = 2; i < argc; i++)
{
    long value = strtol(argv[i], NULL, 10);
    if (value > max)
        max = value;
}

This also works correctly when all supplied numbers are negative.

18.13 Average of Command Line Numbers

long sum = 0;
for (int i = 1; i < argc; i++)
    sum += strtol(argv[i], NULL, 10);

double average = (double)sum / (argc - 1);

Convert an operand before dividing if you need a fractional average. Storing an already truncated integer quotient in a double cannot recover its lost fraction.

18.14 Passing Words and Text

Arguments do not have to be numbers. They can be names, commands, modes, file names or other text.

program.exe hello CodeBhavya

Then argv[1] is "hello" and argv[2] is "CodeBhavya".

18.15 Arguments Containing Spaces

Most shells split unquoted spaces into separate arguments. Quote text such as "C Programming" when it should be received as one argument.

program.exe "CodeBhavya C Programming"

The shell normally removes the grouping quotes before launching the program. The exact quoting rules depend on the shell; the C program receives the resulting strings through argv.

18.16 Checking the Number of Arguments

Never access an argument index that is not available.

if (argc != 3)
{
    printf("Usage: program number1 number2\n");
    return 1;
}
Common confusion: If you need two user values, do not check argc == 2. The program name is also counted, so the expected count is normally 3.

18.17 Command Line Argument Diagram

Command: program.exe 25 40 │ │ │ ▼ ▼ ▼ argv[0] argv[1] argv[2] │ │ │ program "25" "40" │ │ convert convert │ │ 25 40 \ / \ / process

18.18 Command Line Arguments vs scanf()

Command Line Argumentsscanf()
Input is supplied when starting the programInput is read while the program is running
Arrives through argc/argvReads from standard input
Useful for scripts and command-line toolsUseful for interactive console programs
Arguments initially arrive as stringsConversion is specified by the format string

18.19 Building a Command Line Calculator

A small calculator can accept an operator and two operands:

program.exe 12 + 5

A good design is:

Validate argc
↓
Read operator and operands
↓
Convert numeric text
↓
Select operation
↓
Check special cases (such as division by zero)
↓
Print result

18.20 Passing a File Name

program.exe students.txt

Then argv[1] can be used as the file name passed to functions such as fopen(). This connects command-line arguments with practical file-processing utilities.

18.21 A Reliable Problem-Solving Method

1. Count

Determine how many user arguments are required.

2. Validate

Check argc before reading argv[i].

3. Convert

Use appropriate conversion for numeric input.

4. Process

Apply the normal C algorithm after validation.

5. Report

Print useful output or a clear usage message.

18.22 Common Command Line Mistakes

  • Using argv[1] without checking argc.
  • Forgetting that argv contains strings.
  • Trying to perform numeric arithmetic directly on argument strings.
  • Assuming argv[0] is a user-supplied value.
  • Using atoi() when detailed validation is required.
  • Forgetting division-by-zero checks.
  • Using an incorrect loop boundary and reading past argv[argc - 1].
  • Ignoring negative values when calculating minimum or maximum.
  • Forgetting that spaces can separate arguments at the command-line level.

18.23 Interview-Level Understanding

Placement point: Be able to explain why argc includes the program name, why argv contains strings, how to validate argument count, and how to safely convert numeric text.

Treat an argument as input to be checked, just like a typed value or a file record. Conversion checks and arithmetic checks are separate: even two valid integers can overflow when added.

18.24 CodeBhavya Rule

📌 Count → Validate → Convert → Process → Report.

Do not treat command-line text as trusted numeric data until the program has checked and converted it.

18.25 Validate strtol End Pointers and Range Errors

Before strtol, set errno to 0. After it, compare the end pointer with the starting pointer to detect no digits, check the remaining text, and check errno for ERANGE. Finally, check the destination type’s range if it is narrower than long.

Complete C program:

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

int main(int argc, char *argv[])
{
    if (argc != 2) { fputs("Usage: program NUMBER\n", stderr); return 1; }
    char *end;
    errno = 0;
    long n = strtol(argv[1], &end, 10);
    if (end == argv[1] || *end != '\0' || errno == ERANGE ||
        n < INT_MIN || n > INT_MAX) {
        fputs("Invalid integer\n", stderr);
        return 1;
    }
    printf("Number: %ld\n", n);
    return 0;
}

Expected output:

Number: 25

Step-by-step explanation:

  1. Compile into an executable named program and run it with argument 25.
  2. argv[1] is converted to long.
  3. The condition rejects an empty argument, text with no number, an unwanted suffix, a value outside int range, and a conversion range error.
Remember: Run the executable with argument 25 for the sample result. Try 25abc and an empty quoted argument too. This example accepts leading whitespace, but rejects trailing whitespace because it requires the end pointer to reach the terminator.

18.26 Quick Revision

📌 argc → Number of command-line arguments, including the program name

📌 argv → Array of argument strings

📌 argv[0] → Usually the program name

📌 argv[1] → First user-supplied argument

📌 atoi() → Simple string-to-int conversion

📌 strtol() → More robust integer conversion

📌 argc & argv → Used to receive command-line input
INTERACTIVE LEARNING

🎬 Command Line Arguments — argc & argv Flow

Follow how terminal arguments become argc and argv values inside main().

PROGRAM TRACING

🔎 Program Tracing — Command Line Arguments

Trace argc, argv, string-to-integer conversion, and a simple command-line calculation.

18.27 Quick MCQs

Select an answer first, then click Check Answer. A correct choice becomes green. If the answer is wrong, your choice becomes red and the correct option becomes green. The explanation appears below.

1. What does argc represent?
2. What does argv represent?
3. Which argument normally contains the program name?
4. If a program is run as: program.exe 10 20, what is argc?
5. What type of data does argv contain?
6. Which function can convert a string to int?
7. Which function provides more robust integer conversion and error handling?
8. Which header declares atoi() and strtol()?
9. Which should be checked before using argv[2]?
10. Command line arguments are most directly useful for:
PRACTICE

18.28 🎯 Practice Problems

Practice argc, argv, numeric conversion, validation, quoted arguments, file names, and command-line applications. Enter only the arguments in the Command Line Arguments box.

📈 Command Line Arguments Practice Progress
Solved 0 / 20
Completed with Solution 0
Total Score 0 / 400
Completion 0%
A problem counts as Solved when all test cases pass without opening the full solution. Problems completed after viewing the official solution are tracked separately.
1. Display All User Arguments

Problem 1: Display all user-supplied command-line arguments in order. Exclude argv[0] because its exact value is platform-dependent.

Command Line: Command-line arguments, for example: red green blue

Output: Print each user argument on a new line.

2. Display argc and argv Indices

Problem 2: Display argc and every user argument with its argv index. Represent argv[0] with the literal <program> so the output is deterministic in the online judge.

Command Line: Command-line arguments, for example: 10 20

Output: Print argc, then argv[0] as <program>, followed by each user argument and index.

3. Print the First User Argument

Problem 3: Print the first user-supplied command-line argument.

Command Line: At least one command-line argument.

Output: Print argv[1].

4. Add Two Command-Line Numbers

Problem 4: Add two integers supplied as command-line arguments.

Command Line: Two integer arguments.

Output: Print their sum.

5. Subtract Two Command-Line Numbers

Problem 5: Subtract the second command-line integer from the first.

Command Line: Two integer arguments.

Output: Print a - b.

6. Multiply Two Command-Line Numbers

Problem 6: Multiply two integers supplied through command-line arguments.

Command Line: Two integer arguments.

Output: Print the product.

7. Divide Two Command-Line Numbers Safely

Problem 7: Divide the first command-line number by the second and handle division by zero.

Command Line: Two integer arguments.

Output: Print the quotient to two decimals, or "Division by zero".

8. Sum of N Command-Line Numbers

Problem 8: Find the sum of all numeric command-line arguments.

Command Line: One or more integer arguments.

Output: Print their sum.

9. Average of N Command-Line Numbers

Problem 9: Find the average of all numeric user arguments.

Command Line: One or more numeric arguments.

Output: Print the average to two decimal places.

10. Largest Command-Line Number

Problem 10: Find the largest integer supplied on the command line.

Command Line: One or more integer arguments.

Output: Print the largest integer.

11. Smallest Command-Line Number

Problem 11: Find the smallest integer supplied on the command line.

Command Line: One or more integer arguments.

Output: Print the smallest integer.

12. Count Even Command-Line Numbers

Problem 12: Count how many user arguments are even integers.

Command Line: Zero or more integer arguments.

Output: Print the count of even values.

13. Count Positive and Negative Numbers

Problem 13: Count positive and negative command-line integers. Ignore zeros.

Command Line: Zero or more integer arguments.

Output: Print Positive = P and Negative = N.

14. Command-Line Calculator

Problem 14: Create a calculator using two numeric arguments and one operator argument: +, -, *, or /.

Command Line: Three arguments, for example: 12 + 8. Quote "*" as "*" when needed by a shell.

Output: Print the result to two decimal places, or Division by zero / Invalid operator.

15. Student Name and Marks

Problem 15: Accept a student's name and marks through command-line arguments and display them. A name containing spaces should be quoted.

Command Line: Two arguments, for example: "Venu Gopal" 88.5

Output: Print Name and Marks.

16. Accept and Open a File Name

Problem 16: Accept a file name through the command line, open it for writing, and report success.

Command Line: One safe file-name argument, for example: notes.txt

Output: Print File Opened if fopen() succeeds.

17. Count User Arguments

Problem 17: Count command-line arguments excluding the program name.

Command Line: Any number of command-line arguments.

Output: Print argc - 1.

18. Longest Command-Line String

Problem 18: Find the longest user-supplied command-line string. Quoted text with spaces counts as one argument.

Command Line: Two or more arguments, for example: C "Data Structures" AI

Output: Print the longest argument.

19. Validate Integers with strtol()

Problem 19: Convert every command-line argument using strtol() and reject the first argument that is not a complete valid base-10 integer.

Command Line: One or more argument strings.

Output: Print "Valid" if all are valid integers; otherwise print Invalid: value.

20. Command-Line Student Result

Problem 20: Accept a student's name and marks in three subjects through command-line arguments and display total, average, and grade.

Command Line: Four arguments: name, mark1, mark2, mark3. Quote a name containing spaces.

Output: Print Name, Total, Average, and Grade using A for >=90, B for >=75, C for >=60, D for >=50, otherwise F.

18.29 Key Takeaway

🎯 Remember:

argc → How many arguments?

argv → What are the arguments?

argv[0] → Usually program name

argv[1] → First user argument

atoi() → Simple string → int

strtol() → Robust string → integer conversion

Always check argc before accessing argv elements.
INTERVIEW PREPARATION

🎤 Command Line Arguments — Interview Questions

1. What do argc and argv represent?
2. Why should argc be checked before argv[i] is used?
3. Why are numeric command-line arguments still strings?
4. Why is strtol() usually better than atoi() for validated input?
5. How can a single argument contain spaces?
6. What is typically stored in argv[0]?
7. How many user arguments are present when argc is 5?
8. What is a common command-line programming mistake?
PLACEMENT TIPS

💡 Command Line Arguments — Placement Tips

  • Before accessing argv[n], verify that argc > n.
  • Remember that every command-line argument arrives as a string, even when it looks like a number.
  • Prefer strtol() or related conversion functions when invalid input must be detected reliably.
  • When a value contains spaces, it generally needs quoting in the command line so that it reaches the program as one argument.
  • argv[0] is normally the program invocation name; user arguments usually begin at argv[1].
  • For calculator and utility programs, validate both the argument count and the content before performing the requested operation.
EXTRA PRACTICE

✍️ Command Line Arguments — Extra Practice Questions

  1. Sort all integer command-line arguments in ascending order.
  2. Count how many command-line strings are valid floating-point numbers.
  3. Create a command-line unit converter such as 12 km miles.
  4. Accept a file name and a search word, then count occurrences of the word in that file.
  5. Support options such as --sum, --max, and --min followed by numbers.
  6. Build a command-line student grade utility that validates every mark using strtol().
← Previous Topic: Dynamic Memory Allocation Next Topic: Bitwise Programming →