CodeBlanks Logo Icon CodeBlanks

Argument processing

  • C course
  • Intermediate
  • Lesson 89/116
  • 5 min

Learn to process arguments by looping over argv.

Loop over arguments

To process arguments you set up a for loop from argv[1] to argv[argc-1]. At each step argv[i] gives the corresponding string.

Example: for (int i = 1; i < argc; i++) printf("%s\n", argv[i]);. The loop starts at i = 1 because argv[0] is the program name and is usually skipped. The %s conversion prints a string. This pattern underlies tools that take multiple inputs such as file lists or search terms.

Simulated arguments

To try the argument-processing pattern without run-time input, declare a local array resembling argv. This keeps the output always the same.

Example: char *args[] = {"prog", "apple", "pear"}; int n = 3;. Then for (int i = 1; i < n; i++) printf("%s\n", args[i]);. This technique helps when testing command-line tools: put a fixed array in place of real argv and verify the expected output. The same loop pattern works for both simulation and real arguments.

Practice Print simulated arguments

Declare char *args[] = {"prog", "elma", "armut", "portakal"}; and int n = 4;. Loop with for (int i = 1; i < n; i++) and print each argument with printf("%s\n", args[i]);.

Starter code

main.c
#include <stdio.h>

// Define the args array and the count n
// Loop over each argument and print it

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    char *args[] = {"prog", "elma", "armut", "portakal"};
    int n = 4;
    for (int i = 1; i < n; i++) {
        printf("%s\n", args[i]);
    }
    return 0;
}

Expected output

elma
armut
portakal

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the loop parts

Term Meaning
i = 1 Start value
i < argc Continuation test
i++ Step increment
argv[i] Current string

2 Why does the loop start at i = 1?

  • Because loops must start at 1
  • Because argc cannot be at least 1
  • Because argv[0] is always NULL
  • Because argv[0] is the program name Correct answer

Explanation: argv[0] holds the program name; real user arguments start at argv[1].

3 Complete the loop condition

Question
for (int i = 1; i < ____; i++)
Answer
for (int i = 1; i < argc; i++)

Explanation: The test i < argc runs the loop up to the last argument.

All lessons in Intermediate