Challenge - 5 Problems
Atoi Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of atoi with leading spaces and signs
What is the output of the following C code that uses atoi to convert a string with spaces and signs?
DSA C
#include <stdio.h> #include <stdlib.h> int main() { char str[] = " -1234abc"; int val = atoi(str); printf("%d\n", val); return 0; }
Attempts:
2 left
💡 Hint
atoi ignores leading spaces and stops at first non-digit after optional sign.
✗ Incorrect
The atoi function skips leading spaces, reads the optional '-' sign, then converts digits until a non-digit character is found. So it converts " -1234abc" to -1234.
❓ Predict Output
intermediate2:00remaining
Result of atoi on string with no digits
What will be printed by this C program using atoi on a string with no digits?
DSA C
#include <stdio.h> #include <stdlib.h> int main() { char str[] = "abc"; int val = atoi(str); printf("%d\n", val); return 0; }
Attempts:
2 left
💡 Hint
atoi returns 0 if no valid conversion is possible.
✗ Incorrect
Since the string "abc" does not start with digits or sign, atoi returns 0.
❓ Predict Output
advanced2:00remaining
Output of atoi with multiple signs
What is the output of this C code using atoi on a string with multiple signs?
DSA C
#include <stdio.h> #include <stdlib.h> int main() { char str[] = "--123"; int val = atoi(str); printf("%d\n", val); return 0; }
Attempts:
2 left
💡 Hint
atoi stops conversion if invalid sign sequence is found.
✗ Incorrect
The string "--123" is invalid for atoi because it expects at most one sign at the start. Conversion stops immediately and returns 0.
❓ Predict Output
advanced2:00remaining
Value returned by atoi on integer overflow
What is the output of this C program when atoi converts a string representing a number larger than INT_MAX?
DSA C
#include <stdio.h> #include <stdlib.h> #include <limits.h> int main() { char str[] = "999999999999999999999"; int val = atoi(str); printf("%d\n", val); return 0; }
Attempts:
2 left
💡 Hint
atoi does not handle overflow safely; result is undefined.
✗ Incorrect
The atoi function does not check for overflow. Converting a very large number causes undefined behavior and the returned value depends on the system.
🧠 Conceptual
expert2:00remaining
Behavior of atoi with embedded null character
Consider the string literal "123\0abc" passed to atoi. What integer value does atoi return?
Attempts:
2 left
💡 Hint
Strings in C end at the first null character.
✗ Incorrect
The embedded null character '\0' marks the end of the string. atoi reads only "123" and returns 123.
