Challenge - 5 Problems
While Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple while loop
What is the output of this C program?
C
#include <stdio.h> int main() { int i = 1; while (i <= 3) { printf("%d ", i); i++; } return 0; }
Attempts:
2 left
💡 Hint
Look at the condition and how the variable i changes inside the loop.
✗ Incorrect
The loop starts with i=1 and runs while i is less than or equal to 3. It prints i and then increases it by 1. So it prints 1, 2, and 3.
❓ Predict Output
intermediate2:00remaining
While loop with break statement
What will this program print?
C
#include <stdio.h> int main() { int i = 0; while (1) { if (i == 3) { break; } printf("%d ", i); i++; } return 0; }
Attempts:
2 left
💡 Hint
The loop runs forever until the break condition is met.
✗ Incorrect
The loop prints i starting from 0. When i reaches 3, the break stops the loop before printing 3.
🔧 Debug
advanced2:00remaining
Identify the error in this while loop
What error does this code produce when compiled or run?
C
#include <stdio.h> int main() { int i = 0; while (i < 5) printf("%d ", i); i++; return 0; }
Attempts:
2 left
💡 Hint
Check which statements are inside the loop and which are not.
✗ Incorrect
Only the printf is inside the loop because there are no braces. The i++ is outside, so i never changes inside the loop, causing an infinite loop printing 0.
🧠 Conceptual
advanced2:00remaining
While loop behavior with post-increment
What is the value of variable i after this loop finishes?
C
#include <stdio.h> int main() { int i = 0; while (i++ < 5) { // empty body } printf("%d", i); return 0; }
Attempts:
2 left
💡 Hint
Remember that i++ returns the value before incrementing.
✗ Incorrect
The condition i++ < 5 uses post-increment: it checks the current value of i against 5, then increments i regardless. The loop runs 5 times (when i=0 to 4), setting i to 1-5. When i=5, 5 < 5 is false, but i increments to 6 before exiting. So i is 6.
🚀 Application
expert2:00remaining
Count digits in an integer using while loop
What is the output of this program?
C
#include <stdio.h> int main() { int n = 12345, count = 0; while (n > 0) { n = n / 10; count++; } printf("%d", count); return 0; }
Attempts:
2 left
💡 Hint
Each division by 10 removes one digit from the number.
✗ Incorrect
The loop divides n by 10 until n becomes 0. Each division removes one digit. The count increments each time, so it counts digits.