C command-line args: sum argv values with atoi, including argv[0] which converts to 0 if non-numeric.
/* myprog.c */
#include
#include
int main(int argc, char **argv)
{
int i, j = 0;
for (i = 0; i < argc; i++)
j = j + atoi(argv[i]);
printf("%d
", j);
return 0;
}
Executed as: myprog 1 2 3
-
A123
-
B6
-
CError
-
D"123"
Answer
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