Lesson 11 of 34

while and do-while Loops

8 min 25 XP

Use while when you don't know in advance how many times to loop. It runs until the condition becomes false. Forget to change the condition and the loop never ends!

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

do-while checks its condition at the end, so the body always runs at least once.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

n % 10 gives the last digit and n / 10 removes it. These two tricks solve most digit problems in interviews.

Challenge

+25 XP

Read a number and print the sum of its digits. Input: 4721 → Output: 14

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.