Complete the code to access the first command line argument.
#include <stdio.h> int main(int argc, char *argv[]) { printf("First argument: %s\n", argv[[1]]); return 0; }
The first command line argument is stored at argv[1]. argv[0] is the program name.
Complete the code to check if at least one command line argument is provided.
#include <stdio.h> int main(int argc, char *argv[]) { if (argc [1] 1) { printf("Argument provided\n"); } else { printf("No argument provided\n"); } return 0; }
We check if argc > 1 because argc counts the program name plus arguments.
Fix the error in the code to print all command line arguments.
#include <stdio.h> int main(int argc, char *argv[]) { for (int i = 1; i [1] argc; i++) { printf("Argument %d: %s\n", i, argv[i]); } return 0; }
The loop should run while i < argc because argv[argc] is NULL and out of bounds.
Fill both blanks to create a program that prints the number of arguments excluding the program name.
#include <stdio.h> int main(int argc, char *argv[]) { int count = argc [1] 1; printf("Number of arguments: %d\n", [2]); return 0; }
Subtract 1 from argc to exclude the program name, then print count.
Fill all three blanks to create a program that prints each argument and its length.
#include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { for (int i = 1; i [1] argc; i++) { printf("Argument: %[2], Length: %d\n", argv[i], [3](argv[i])); } return 0; }
The loop runs while i < argc. Use %s to print strings and strlen to get the length.