C command-line args: sum argv values with atoi, including argv[0] which converts to 0 if non-numeric.\n\n/* myprog.c */\n#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char **argv)\n{\n int i, j = 0;\n for (i = 0; i < argc; i++)\n j = j + atoi(argv[i]);\n printf("%d\n", j);\n return 0;\n}\n\nExecuted as: myprog 1 2 3

Difficulty: Medium

Correct Answer: 6

Explanation:


Introduction / Context:
This C program demonstrates how command-line arguments are received via argc and argv, how atoi parses strings into integers, and why argv[0] does not break the sum even though it is the program name. Understanding iteration over argv and numeric conversion behavior is essential for basic CLI handling.


Given Data / Assumptions:

  • Program is invoked as: myprog 1 2 3.
  • argc counts all tokens, including program name → argc = 4.
  • argv[0] is the program name string "myprog"; argv[1]..argv[3] are "1", "2", "3".
  • atoi returns 0 for non-numeric prefixes and normal integers for valid strings.


Concept / Approach:
The loop sums atoi(argv[i]) for i = 0..argc-1. atoi("myprog") → 0. atoi("1") → 1, atoi("2") → 2, atoi("3") → 3. Therefore the total is 0 + 1 + 2 + 3 = 6.


Step-by-Step Solution:

Initialize j = 0.i = 0 → atoi(argv[0]) = 0 → j = 0.i = 1 → atoi("1") = 1 → j = 1.i = 2 → atoi("2") = 2 → j = 3.i = 3 → atoi("3") = 3 → j = 6.


Verification / Alternative check:
Replacing atoi with strtol would also yield the same sums here; testing with additional non-numeric args also demonstrates atoi returns 0 when no leading digits are present.


Why Other Options Are Wrong:

  • 123: Concatenation, not addition; program adds numbers.
  • Error: Code is valid and compiles.
  • "123": String form; program prints an integer.


Common Pitfalls:
Forgetting argv[0] is included; assuming atoi would fail or crash on non-numeric strings; expecting string concatenation instead of arithmetic.


Final Answer:
6

More Questions from Command Line Arguments

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion