Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to access the first command-line argument.
C
#include <stdio.h> int main(int argc, char *argv[]) { printf("First argument: %s\n", argv[[1]]); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using argv[0] which is the program name, not the first argument.
Using argc as an index which is invalid.
✗ Incorrect
The first command-line argument is stored at argv[1]. argv[0] is the program name.
2fill in blank
mediumComplete the code to check if at least two arguments are passed.
C
#include <stdio.h> int main(int argc, char *argv[]) { if (argc [1] 3) { printf("Two or more arguments provided.\n"); } else { printf("Less than two arguments.\n"); } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking if argc == 2 which means only one argument.
Using < instead of >= causing wrong condition.
✗ Incorrect
Since argc counts the program name, at least two arguments means argc >= 3.
3fill in blank
hardFix the error in accessing the last argument.
C
#include <stdio.h> int main(int argc, char *argv[]) { printf("Last argument: %s\n", argv[[1]]); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using argc as index which is out of bounds.
Using argc + 1 which is invalid index.
✗ Incorrect
The last argument is at index argc - 1 because argc counts all arguments including the program name.
4fill in blank
hardFill both blanks to print all arguments except the program name.
C
#include <stdio.h> int main(int argc, char *argv[]) { for (int i = [1]; i [2] argc; i++) { printf("Argument %d: %s\n", i, argv[i]); } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting loop at 0 which prints program name.
Using <= which causes out of bounds access.
✗ Incorrect
Start from 1 to skip program name, and loop while i < argc to stay within bounds.
5fill in blank
hardFill all three blanks to print the number of arguments excluding the program name.
C
#include <stdio.h> int main(int argc, char *argv[]) { int count = argc [1] [2]; printf("Number of arguments: %d\n", [3]); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Adding 1 instead of subtracting.
Printing argc instead of count.
✗ Incorrect
Subtract 1 from argc to exclude the program name, then print the count variable.