KwickCards Java
How many times does each loop print?

ICSE · LOOPS
while vs do-while
How many times does each loop print?
int i = 10;
while (i < 5) {
System.out.print(i);
}
do {
System.out.print(i);
} while (i < 5);The difference between while and do-while is a classic ICSE question.
If int i = 10 and the condition is i < 5, a while loop will not run at all, but a do-while loop will run its body once before checking the condition.
Use do-while when the body must execute at least once, such as showing a menu before asking for the choice.
Do not forget the semicolon at the end of a do-while, it is a common error.
Answer: the while loop prints nothing, and the do-while prints 10 once.
More on this: free Java lessons
More Java cards
ICSE Java
ISC CS
Java Output
Index the letters of BlueJ
Math methods: watch the return type
Trace a for loop that adds 3Written by Kajal Mehta (Kajal Ma'am), MCA, teaching computer subjects since 2004. All KwickCards · KwickAcademy

