💻 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().
↓
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:
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[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
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 - bMultiplication
a * bDivision
a / bCheck 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;
}
argc == 2. The program name is also counted, so the expected count is normally 3.18.17 Command Line Argument Diagram
18.18 Command Line Arguments vs scanf()
| Command Line Arguments | scanf() |
|---|---|
| Input is supplied when starting the program | Input is read while the program is running |
Arrives through argc/argv | Reads from standard input |
| Useful for scripts and command-line tools | Useful for interactive console programs |
| Arguments initially arrive as strings | Conversion 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:
↓
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 checkingargc. - Forgetting that
argvcontains 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
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
Do not treat command-line text as trusted numeric data until the program has checked and converted it.
18.25 Quick Revision
📌 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
🎬 Command Line Arguments — argc & argv Flow
Follow how terminal arguments become argc and argv
values inside main().
🎬 argc & argv Visualizer
Example command: program 10 20
🔎 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.
argc is the argument count supplied to main(), including argv[0].
argv is the argument vector: an array of pointers to character strings.
argv[0] conventionally contains the program name or invocation name.
There are three argv elements: program.exe, 10, and 20.
Each command-line argument is supplied as a character string.
atoi() converts a numeric string to int, but it provides limited error reporting.
strtol() provides an end pointer and supports more reliable validation than atoi().
Both atoi() and strtol() are declared in stdlib.h.
The program should verify that argc is large enough before accessing argv[2].
Command-line arguments provide values when the program is started.
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.
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.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; i++)
{
printf("%s", argv[i]);
if (i < argc - 1)
printf("\n");
}
return 0;
}
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.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("argc = %d\n", argc);
printf("argv[0] = <program>");
for (int i = 1; i < argc; i++)
printf("\nargv[%d] = %s", i, argv[i]);
return 0;
}
Problem 3: Print the first user-supplied command-line argument.
Command Line: At least one command-line argument.
Output: Print argv[1].
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Missing Argument");
return 0;
}
printf("%s", argv[1]);
return 0;
}
Problem 4: Add two integers supplied as command-line arguments.
Command Line: Two integer arguments.
Output: Print their sum.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#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", a + b);
return 0;
}
Problem 5: Subtract the second command-line integer from the first.
Command Line: Two integer arguments.
Output: Print a - b.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 3)
return 1;
printf("%d", atoi(argv[1]) - atoi(argv[2]));
return 0;
}
Problem 6: Multiply two integers supplied through command-line arguments.
Command Line: Two integer arguments.
Output: Print the product.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 3)
return 1;
long a = strtol(argv[1], NULL, 10);
long b = strtol(argv[2], NULL, 10);
printf("%ld", a * b);
return 0;
}
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".
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 3)
return 1;
double a = strtod(argv[1], NULL);
double b = strtod(argv[2], NULL);
if (b == 0.0)
{
printf("Division by zero");
return 0;
}
printf("%.2f", a / b);
return 0;
}
Problem 8: Find the sum of all numeric command-line arguments.
Command Line: One or more integer arguments.
Output: Print their sum.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
long sum = 0;
for (int i = 1; i < argc; i++)
sum += strtol(argv[i], NULL, 10);
printf("%ld", sum);
return 0;
}
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.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc < 2)
return 1;
double sum = 0.0;
for (int i = 1; i < argc; i++)
sum += strtod(argv[i], NULL);
printf("%.2f", sum / (argc - 1));
return 0;
}
Problem 10: Find the largest integer supplied on the command line.
Command Line: One or more integer arguments.
Output: Print the largest integer.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc < 2)
return 1;
long maximum = strtol(argv[1], NULL, 10);
for (int i = 2; i < argc; i++)
{
long value = strtol(argv[i], NULL, 10);
if (value > maximum)
maximum = value;
}
printf("%ld", maximum);
return 0;
}
Problem 11: Find the smallest integer supplied on the command line.
Command Line: One or more integer arguments.
Output: Print the smallest integer.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc < 2)
return 1;
long minimum = strtol(argv[1], NULL, 10);
for (int i = 2; i < argc; i++)
{
long value = strtol(argv[i], NULL, 10);
if (value < minimum)
minimum = value;
}
printf("%ld", minimum);
return 0;
}
Problem 12: Count how many user arguments are even integers.
Command Line: Zero or more integer arguments.
Output: Print the count of even values.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int count = 0;
for (int i = 1; i < argc; i++)
{
long value = strtol(argv[i], NULL, 10);
if (value % 2 == 0)
count++;
}
printf("%d", count);
return 0;
}
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.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int positive = 0;
int negative = 0;
for (int i = 1; i < argc; i++)
{
long value = strtol(argv[i], NULL, 10);
if (value > 0)
positive++;
else if (value < 0)
negative++;
}
printf("Positive = %d\nNegative = %d", positive, negative);
return 0;
}
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.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 4)
return 1;
double a = strtod(argv[1], NULL);
char op = argv[2][0];
double b = strtod(argv[3], NULL);
switch (op)
{
case '+': printf("%.2f", a + b); break;
case '-': printf("%.2f", a - b); break;
case '*': printf("%.2f", a * b); break;
case '/':
if (b == 0.0) printf("Division by zero");
else printf("%.2f", a / b);
break;
default: printf("Invalid operator");
}
return 0;
}
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.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 3)
return 1;
double marks = strtod(argv[2], NULL);
printf("Name = %s\nMarks = %.1f", argv[1], marks);
return 0;
}
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.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc != 2)
return 1;
FILE *fp = fopen(argv[1], "w");
if (fp == NULL)
{
printf("Open Failed");
return 0;
}
printf("File Opened");
fclose(fp);
return 0;
}
Problem 17: Count command-line arguments excluding the program name.
Command Line: Any number of command-line arguments.
Output: Print argc - 1.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
int main(int argc, char *argv[])
{
(void)argv;
printf("%d", argc - 1);
return 0;
}
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.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc < 2)
return 1;
int best = 1;
for (int i = 2; i < argc; i++)
{
if (strlen(argv[i]) > strlen(argv[best]))
best = i;
}
printf("%s", argv[best]);
return 0;
}
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.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; i++)
{
char *end;
errno = 0;
long value = strtol(argv[i], &end, 10);
if (errno == ERANGE || end == argv[i] || *end != '\0')
{
printf("Invalid: %s", argv[i]);
return 0;
}
(void)value;
}
printf("Valid");
return 0;
}
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.
C Code Editor
Command Line Arguments
Program Output
Run your program to see the output.
Test Cases
"Venu Gopal" 88.5.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 5)
return 1;
double m1 = strtod(argv[2], NULL);
double m2 = strtod(argv[3], NULL);
double m3 = strtod(argv[4], NULL);
double total = m1 + m2 + m3;
double average = total / 3.0;
char grade;
if (average >= 90) grade = 'A';
else if (average >= 75) grade = 'B';
else if (average >= 60) grade = 'C';
else if (average >= 50) grade = 'D';
else grade = 'F';
printf("Name = %s\n", argv[1]);
printf("Total = %.1f\n", total);
printf("Average = %.2f\n", average);
printf("Grade = %c", grade);
return 0;
}
18.28 Key Takeaway
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.
🎤 Command Line Arguments — Interview Questions
💡 Command Line Arguments — Placement Tips
- Before accessing
argv[n], verify thatargc > 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 atargv[1].- For calculator and utility programs, validate both the argument count and the content before performing the requested operation.
✍️ Command Line Arguments — Extra Practice Questions
- Sort all integer command-line arguments in ascending order.
- Count how many command-line strings are valid floating-point numbers.
- Create a command-line unit converter such as
12 km miles. - Accept a file name and a search word, then count occurrences of the word in that file.
- Support options such as
--sum,--max, and--minfollowed by numbers. - Build a command-line student grade utility that validates every mark using
strtol().