Placement Prep

C Command Line Arguments Set 2: 5 Placement Programs

Five C programs using argc/argv for placement interviews: sum of CLI args, even/odd count, string reverse, safe atoi parsing, and multi-arg processing.

By FACE Prep Team 6 min read
c-programming command-line-arguments argc-argv placement-prep c-interview-questions

Five programs cover the patterns placement tests repeat most: sum of CLI args, even/odd count, string reverse, safe integer parsing, and multi-arg inspection.

This is Set 2 of FACE Prep’s command line arguments series. Set 1 covers the fundamentals: what argc and argv mean, simple single-argument loops, and a first look at atoi. Set 2 raises the complexity to match what TCS, Wipro, and Infosys coding rounds actually probe: arithmetic across multiple arguments, in-place string manipulation, and safe conversion that distinguishes "0" from "abc".

Why argv Programs Appear in Placement Tests

Placement coding rounds test whether a student can read structured input, validate it, and process it without a runtime crash. Command line argument programs compress all three into 20–30 lines of C: the student must handle missing arguments (segfault risk), convert strings to numbers (silent-zero risk with atoi), and loop correctly over an unknown argument count (off-by-one risk).

Three things separate a passing answer from a failing one in a timed invigilated test:

  • Guarding argc before accessing argv[1]
  • Using the correct loop bound (i < argc, not i <= argc)
  • Checking conversion validity when the marks scheme includes invalid-input test cases

Set 2 programs address all three in context. Work through each one; the edge cases in the explanations are the questions interviewers ask.

argc and argv: A Two-Minute Recap

The C standard definition of main specifies the hosted-program entry point as:

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

Key facts:

  • argc is always at least 1. argv[0] holds the program name or an empty string.
  • argv[1] through argv[argc-1] are the user-supplied arguments, each a null-terminated string.
  • argv[argc] is guaranteed to be NULL by the standard — useful as a loop sentinel.

If you run ./sum 10 20 30, then argc is 4, argv[0] is "./sum", argv[1] is "10", argv[2] is "20", and argv[3] is "30".

The loop pattern used in all five programs below:

for (int i = 1; i < argc; i++) {
    /* process argv[i] */
}

i = 1 skips the program name. i < argc stops before the NULL sentinel. Both of these are non-negotiable for correct behaviour.

Five Programs: Arithmetic and String Operations

1. Sum of Integer Arguments

Accept any number of integers on the command line and print their total. This is the most common argv arithmetic variant in Tier-2 college placement tests.

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

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: %s <num1> <num2> ...\n", argv[0]);
        return 1;
    }
    int sum = 0;
    for (int i = 1; i < argc; i++) {
        sum += atoi(argv[i]);
    }
    printf("Sum: %d\n", sum);
    return 0;
}
  • Compile: gcc sum.c -o sum
  • Run: ./sum 10 20 30
  • Output: Sum: 60

What this tests: atoi converts "10" to integer 10. The argc guard prevents a crash when called with no arguments. Interviewers sometimes run the program with zero args specifically to check whether it crashes.

2. Count Even and Odd Numbers

Same loop as Program 1, with a conditional branch. This pattern appears verbatim in Wipro NLTH output-prediction questions.

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

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: %s <num1> <num2> ...\n", argv[0]);
        return 1;
    }
    int even = 0, odd = 0;
    for (int i = 1; i < argc; i++) {
        int n = atoi(argv[i]);
        if (n % 2 == 0)
            even++;
        else
            odd++;
    }
    printf("Even: %d, Odd: %d\n", even, odd);
    return 0;
}
  • Run: ./evenodd 1 2 3 4 5
  • Output: Even: 2, Odd: 3

Edge cases interviewers probe:

  • When n = 0: zero satisfies 0 % 2 == 0, so the even counter increments correctly.
  • When n is negative: in C, -4 % 2 evaluates to 0, so negative even numbers are classified correctly.

3. Reverse a String from argv

In-place string reversal on argv[1] avoids extra memory allocation. The two-pointer swap is the expected solution in placement rounds.

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: %s <string>\n", argv[0]);
        return 1;
    }
    char *str = argv[1];
    int len = (int)strlen(str);
    for (int i = 0; i < len / 2; i++) {
        char temp = str[i];
        str[i] = str[len - 1 - i];
        str[len - 1 - i] = temp;
    }
    printf("Reversed: %s\n", str);
    return 0;
}
  • Run: ./reverse placement
  • Output: Reversed: tnemecalp

The loop runs len / 2 times. Integer division handles both even and odd lengths correctly without extra logic. For an odd-length string, the middle character stays in place. To extend this into a palindrome check, compare the reversed string to the original. The palindrome check article covers that variation.

4. Safe Integer Parsing: atoi vs strtol

atoi silently returns 0 for any non-numeric input, with no way to distinguish the string "0" from "abc". The strtol function provides error-detection via an end pointer.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: %s <number>\n", argv[0]);
        return 1;
    }
    char *end;
    errno = 0;
    long val = strtol(argv[1], &end, 10);
    if (*end != '\0' || errno != 0) {
        printf("Invalid input: %s\n", argv[1]);
        return 1;
    }
    printf("Parsed value: %ld\n", val);
    return 0;
}
  • Valid input: ./parse 42Parsed value: 42
  • Invalid input: ./parse abcInvalid input: abc
  • Partial input: ./parse 12abcInvalid input: 12abc

The check *end != '\0' catches partial strings like "12abc" that atoi would silently truncate to 12. The errno check catches overflow. At mid-tier product companies, interviewers ask this distinction directly: “What would your program do with ./sum abc 10?” An answer that mentions strtol and the endptr check gets full marks.

5. Multi-Arg Inspector

This program iterates all arguments and reports the length and type (numeric or alphabetic) of each. It combines strlen, isdigit, and a nested loop over every argv entry, the multi-library pattern that trips students in timed tests.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: %s <arg1> <arg2> ...\n", argv[0]);
        return 1;
    }
    for (int i = 1; i < argc; i++) {
        int is_num = 1;
        for (int j = 0; argv[i][j] != '\0'; j++) {
            if (!isdigit((unsigned char)argv[i][j])) {
                is_num = 0;
                break;
            }
        }
        printf("arg[%d]: \"%s\", length %zu, type: %s\n",
               i, argv[i], strlen(argv[i]),
               is_num ? "numeric" : "string");
    }
    return 0;
}
  • Run: ./inspect hello 123 world 456
  • Output:
    arg[1]: "hello", length 5, type: string
    arg[2]: "123", length 3, type: numeric
    arg[3]: "world", length 5, type: string
    arg[4]: "456", length 3, type: numeric

The cast (unsigned char) in isdigit prevents undefined behaviour on negative char values on platforms where char is signed. This detail separates a careful answer from a fast one in a live interview. The inner break exits early on the first non-digit, which matters for performance when processing long strings.

Common Pitfalls and Edge Cases

Most failed attempts in placement rounds trace back to four recurring mistakes:

  • Off-by-one in the loop: Writing i <= argc instead of i < argc accesses argv[argc], which is NULL. Dereferencing it causes a segfault.
  • Missing the argc guard: Accessing argv[1] without first checking argc >= 2 is undefined behaviour when the program runs with no arguments.
  • Trusting atoi for all cases: atoi("0") and atoi("abc") both return 0. Tests that include non-numeric input will expose this. Use strtol with the end pointer check (Program 4) when correctness matters.
  • In-place argv mutation without a copy: Directly modifying argv[1] in Program 3 works on most compilers, but the C standard makes it implementation-defined. For interview answers that prioritise portability, copy to a char buf[256] before the swap loop.

For the array-based equivalent of finding max and min values, a pattern that often appears in the next round after CLI programs, see Smallest and Largest Element in an Array.

What Comes Next

The atoi/strtol distinction in Program 4 follows the same rule as input parsing in any robust system: accept structured input, validate boundaries, and fail explicitly rather than silently. That principle shows up in every layer of production software, including the APIs that power language models. If the parse-safely-fail-explicitly pattern from Program 4 clicked for you, TinkerLLM runs token-validation exercises that extend the same instinct to LLM prompt inputs (₹299 entry).

For the broader interview path, once C fundamentals are solid and CLI programs are comfortable, Data Structures Interview Questions with Answers covers the arrays, linked lists, and stack patterns that typically appear in later rounds at TCS, Wipro, and Infosys.

Primary sources

Frequently asked questions

What is the difference between argc and argv in C?

argc is an integer count of all arguments including the program name, so it is always at least 1. argv is an array of character pointers where argv[0] is the program name and argv[1] through argv[argc-1] are the user-supplied arguments.

Why does atoi return 0 for invalid input?

atoi has no error-reporting mechanism. Both the string 0 and any non-numeric string like abc produce return value 0. Use strtol with an endptr check to distinguish valid zero from invalid input.

How do I sum numbers passed as command line arguments?

Loop from i=1 to argc-1, convert each argv[i] to an integer with atoi, and add to a running total. Guard with if (argc < 2) before the loop to handle the no-argument case.

Can I modify the strings in argv directly?

The C standard makes this implementation-defined. Most compilers allow in-place modification of argv strings, which is how the string reversal program works. For portable code, copy to a local buffer before modifying.

What is argv[argc] equal to?

The C standard guarantees argv[argc] is NULL. This means you can also iterate with a pointer loop using argv[++i] as the condition, as an alternative to an argc-based for loop.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF