Sunday, May 25, 2025

The Do-while loop

 Next on our list of loops is the do-while loop.

The do-while loop is very similar to the while-loop, with one key difference.

The regular while-loop looks like:

while(something is true){
do this;
}

but the do-while loop looks like:

do {
this;
} while (something is true);

There is a key difference here. The while loop we saw is never guaranteed to execute. The while-loop checks the condition, and if it’s false from the get-go, nothing happens, and we just move on. But the do-while loop, on the other hand, encounters the “do this thing” part of its instructions before it encounters the condition to check. Do-while loops are therefore guaranteed to execute at least once, since they execute, then check, then execute, then check… and so on. Take a moment to realize that {execute, check, execute, check…} could produce different results than {check, execute, check, execute…}

No comments:

Post a Comment

Switch

 Other than if/if-else/if-else if-else and the ternary operator, there is yet another common and important conditional expression in Java th...