basics · intermediate · ~15 min

Count flag arguments

Iterate argv the way a CLI parser does.

Challenge

Count the command-line flags in an argv array, the way a CLI parser starts out.

Task

Implement int count_flags(int argc, char **argv) that returns how many arguments start with a '-'. Skip argv[0] (the program name) and scan argv[1] through argv[argc-1]. No main — the grader calls it.

Input

The argument count int argc and the argument vector char **argv (with argv[0] being the program name).

Output

Returns the number of arguments (after argv[0]) whose first character is '-'.

Example

{"prog","-a","foo","-b"}      ->   2
{"prog"}                       ->   0
{"prog","-x","-y","-z"}        ->   3

Edge cases

  • With only the program name (argc == 1), the count is 0.

Rules

  • Start scanning at index 1 — argv[0] is the program name, not an argument.

Input format

int argc and char **argv (argv[0] is the program name).

Output format

The number of arguments after argv[0] that start with '-'.

Constraints

Skip argv[0]; scan indices 1..argc-1.

Starter code

int count_flags(int argc, char **argv) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.