0% found this document useful (0 votes)
5 views

Mod 3 cmdline arg

Command line arguments in C allow users to pass values to a program at execution, influencing its behavior without code modification. They are accessed in the main() function via parameters argc (argument count) and argv (argument vector). Examples demonstrate how to retrieve and utilize these arguments, including converting strings to integers for calculations.

Uploaded by

shaleen8elza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Mod 3 cmdline arg

Command line arguments in C allow users to pass values to a program at execution, influencing its behavior without code modification. They are accessed in the main() function via parameters argc (argument count) and argv (argument vector). Examples demonstrate how to retrieve and utilize these arguments, including converting strings to integers for calculations.

Uploaded by

shaleen8elza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 5

PROGRAMMING IN C

MODULE 3
COMMAND LINE ARGUMENTS
Command Line Arguments in C
• Command line arguments are used to pass values to a C program
when it is executed (through the terminal or command prompt).
• They allow users to influence the behavior of the program
dynamically without modifying the code.
• These arguments are passed to the main() function and can be
accessed directly within it.
• int main(int argc, char *argv[])
Argument Count: total number of arguments passed
argc
(including program name)
Argument Vector: array of strings representing the
argv[]
arguments
Key Concepts
• argv[0]: name of the program (by default)
• argv[1] to argv[argc-1]: actual command line arguments
• All command line arguments are strings (character arrays)
• Must be converted using functions like atoi(), atof() for numerical
operations
Example 1
#include <stdio.h>

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


printf("Total arguments: %d\n", argc);
Run from terminal like
for (int i = 0; i < argc; i++) { ./a.out hello world 123
Output
printf("Argument %d: %s\n", i, argv[i]); Total arguments: 4
} Argument 0: ./a.out
Argument 1: hello
Argument 2: world
return 0; Argument 3: 123
}
Example 2: Sum of two numbers
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s num1 num2\n", argv[0]);
return 1;
}
int a = atoi(argv[1]); // convert to int Run Like
./a.out 10 20
int b = atoi(argv[2]);
printf("Sum: %d\n", a + b); Output
Sum: 30
return 0;
}

You might also like