π What Youβll Learn
- How the
whileloop works - How the
do...whileloop works - Differences between the two
- Common patterns and pitfalls
- Real-world examples
π What is a While Loop?
A while loop keeps running as long as its condition is true.
π§ Syntax:
while (condition) {
// code to repeat
}
β Example
int i = 1;
while (i <= 5) {
System.out.println("i = " + i);
i++;
}
π This prints i = 1 through i = 5.
π The do...while Loop
This version always runs at least once β because the condition is checked after the first execution.
π§ Syntax:
do {
// code to run
} while (condition);
Example:
int i = 1;
do {
System.out.println("i = " + i);
i++;
} while (i <= 5);
π When to Use Which?
| Use this... | When... |
|---|---|
while |
You may want to skip the loop entirely |
do...while |
You always want it to run at least once |
β οΈ Common Mistakes
- Forgetting to update the loop variable (infinite loop!)
- Misplacing semicolons:
while (i < 5); // β Don't do this - Using assignment instead of comparison:
while (x = 5) // β should be while (x == 5)
π Real-Life Example
Password Retry Simulation:
Scanner scanner = new Scanner(System.in);
String password;
do {
System.out.print("Enter password: ");
password = scanner.nextLine();
} while (!password.equals("java123"));
System.out.println("Access granted!");
π Recap
whileloops check condition before runningdo...whileloops run at least once- Be careful with infinite loops and condition logic