[go: up one dir, main page]

0% found this document useful (0 votes)
5 views2 pages

Command Line Arguments in C

Uploaded by

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

Command Line Arguments in C

Uploaded by

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

Command Line Arguments in C –

What is a Command Line Argument?


• It allows you to pass values (arguments) to your C program from the terminal or command line when
running it.
• Used when you want to give input without writing scanf() or input() in code.

main() Function with Arguments


c
CopyEdit
int main(int argc, char *argv[])
What are these?
Term Meaning
argc Number of command-line arguments passed (argument count)
argv[] Array of strings (char pointers) containing arguments

Example Program
c
CopyEdit
#include <stdio.h>

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


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

for(int i = 0; i < argc; i++) {


printf("Argument %d: %s\n", i, argv[i]);
}

return 0;
}

Build and Run (Steps)


1. Write the code and save as a.c
2. Compile it:
bash
CopyEdit
gcc a.c -o a.exe
3. Run with arguments:
bash
CopyEdit
./a.exe hello world 123
Output:
yaml
CopyEdit
Total Arguments: 4
Argument 0: ./a.exe
Argument 1: hello
Argument 2: world
Argument 3: 123
Notice:
• The first argument argv[0] is always the program name.
• Other arguments follow.

Using atoi() to Convert Strings to Integers


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

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


if (argc < 3) {
printf("Please provide two numbers.\n");
return 1;
}

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

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


return 0;
}
Run like this:
bash
CopyEdit
./a.exe 5 7
Output: Sum = 12

Summary Table
Term Use
argc Tells how many arguments are passed
argv[i] Gets the value of each argument
atoi() Converts string to integer
./a.exe apple banana Example of passing arguments

You might also like