💻 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

Argument count. It tells the program how many argument strings are available, including the program name.

argv

Argument vector. It is an array of pointers to null-terminated character strings.

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

The important point is that the program name occupies 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] is therefore a string, not an integer. This distinction is the foundation of safe command-line programming in C.

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];

First convert the text into the required numeric type.

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 convenient for simple examples, but it does not provide robust error reporting for invalid numeric text. For production-style input validation, 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() lets the program distinguish successful conversion from trailing characters and range errors.

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);

This pattern is useful for sums, counts, minimum/maximum searches and other command-line utilities.

18.12 Finding Maximum and Minimum

A reliable pattern is to initialize the result from the first actual data argument rather than assuming a value such as zero.

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);

The cast matters: without a floating-point operand, integer division can discard the fractional part.

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

When a shell treats spaces as argument separators, text containing spaces must normally be quoted.

program.exe "CodeBhavya C Programming"

The program receives the quoted text as one argument. Exact shell behavior can vary, but the C program still sees the resulting argument 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.

Also remember that command-line argument handling is an interface boundary: input arrives as text, so a robust program should validate it before trusting or processing it.

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 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.26 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.27 🎯 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 / 2000
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.28 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 →