Challenge - 5 Problems
String Input and Output Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this C code snippet?
Consider the following C program. What will it print when run?
C
#include <stdio.h> int main() { char str[10]; scanf("%s", str); printf("Hello, %s!", str); return 0; }
Attempts:
2 left
💡 Hint
Think about what scanf with %s reads and how printf prints it.
✗ Incorrect
The scanf with %s reads a word until whitespace. If the input is 'world', it stores it in str. Then printf prints 'Hello, world!'.
❓ Predict Output
intermediate2:00remaining
What does this code print?
What is the output of this C program?
C
#include <stdio.h> int main() { char s[6] = "Hello"; printf("%s\n", s); return 0; }
Attempts:
2 left
💡 Hint
Remember how strings are stored and printed in C.
✗ Incorrect
The string "Hello" fits in the array s with the null terminator. printf prints the string until the null character, so output is Hello.
❓ Predict Output
advanced2:00remaining
What is the output of this code with fgets?
What will this C program print if the user inputs: Hello World\n?
C
#include <stdio.h> int main() { char buffer[6]; fgets(buffer, 6, stdin); printf("%s", buffer); return 0; }
Attempts:
2 left
💡 Hint
fgets reads up to size-1 characters including newline if present.
✗ Incorrect
fgets reads up to 5 characters (6-1) including the newline if it fits. Input is 'Hello World\n', so buffer contains 'Hello\0'. printf prints 'Hello'.
❓ Predict Output
advanced2:00remaining
What error does this code cause?
What happens when this C code runs?
C
#include <stdio.h> int main() { char str[5]; scanf("%s", str); printf("%s", str); return 0; }
Attempts:
2 left
💡 Hint
Think about how scanf reads strings and array size.
✗ Incorrect
The array str can hold 4 characters plus null terminator. If input is longer than 4 characters, scanf writes beyond array bounds causing buffer overflow.
🧠 Conceptual
expert2:00remaining
How many characters are read by fgets in this code?
Given this code, how many characters maximum will fgets read from input?
C
#include <stdio.h> int main() { char input[10]; fgets(input, sizeof(input), stdin); return 0; }
Attempts:
2 left
💡 Hint
Remember how fgets uses the size parameter.
✗ Incorrect
fgets reads up to size-1 characters and adds a null terminator. Here size is 10, so it reads up to 9 characters plus null terminator.