Lesson 2
Java Space Loops: Mastering While and Do-While
Introduction

Greetings, Future Coder! Let's unravel the while and do-while loops in Java. Picture these loops as cosmic spirals, taking us around the same block of code until we hit the right constellation or condition. First, we'll orbit while loops, then do-while loops, and finally, understand when to use each one.

Introduction to 'while' Loops

Loops automate repetitive tasks, like spiraling around a galaxy until a specific star is spotted. Imagine a race track: our code is the runner, circling laps (repeating the same block of code) until the required number of laps (loop's condition) is completed.

A Java while loop repeatedly executes a block of code as long as its given condition remains true.

Here is the while loop's structure:

Java
1while (condition) { 2 do some action 3}

Here's a simple while loop example that counts down from 5 to 0:

Java
1int countdown = 5; 2while (countdown >= 0) { 3 // The countdown will print the current number and decrease it by 1 in each loop 4 System.out.println(countdown); 5 countdown--; 6} 7// Prints: 8// 5 9// 4 10// 3 11// 2 12// 1 13// 0

Notice the decrementing command countdown--? Without it, our code would become an infinite loop, circling around indefinitely. Be cautious!

Journey with the 'do-while' Loop

Do-while loops execute a block of code once and continue repeating it until the condition becomes false. The syntax is slightly different:

Java
1do { 2 // code executed at least once 3} while (condition);

This loop fits perfectly into scenarios that require at least one execution of the code before checking conditions.

Here's a simple do-while loop example that counts down from 5 to 0:

Java
1int countdown = 5; 2do { 3 // The countdown will print the current number and decrease it by 1 in each loop 4 System.out.println(countdown); 5 countdown--; 6} while (countdown >= 0); 7// Prints: 8// 5 9// 4 10// 3 11// 2 12// 1 13// 0
'while' vs. 'do-while': When to Use Which One

Use a while loop when the execution of the code depends on the condition. Use a do-while loop when you are sure about running it at least once and checking the condition thereafter.

Lesson Summary and Practice

Bravo! You've mastered the while and do-while loops in Java. You've delved into their syntax, understood their usage, and can now decide when to use which one. Gear up for some hands-on practice, and we'll see you on our next cosmic expedition!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.