Module 3 - Lesson 12 - Final!

While Loops: Condition-Based Repetition

For loop က count-based ဆိုရင် while loop က condition-based ပါ။ Condition true į€–į€¼į€…į€ŗį€žį€›į€½į€±į€· code က run ပြီး unknown iterations, user input validation į€œį€­į€Æ scenarios တွေမှာ į€”į€žį€Æį€¶į€øį€™į€»į€¬į€øį€•į€«į€į€šį€ŗį‹

ā±ļø 45 minutes šŸ“š Intermediate šŸ”„ Condition-Based Loops šŸŽ‰ Module 3 Complete!

šŸŽÆ į€žį€„į€ŗ į€žį€„į€ŗį€šį€°į€™į€Šį€·į€ŗ နရာများ

ဒီ lesson မှာ į€žį€„į€ŗ į€žį€„į€ŗį€šį€°į€™į€Šį€·į€ŗ နရာများ:

  • While loop ဆိုတာ į€˜į€¬į€œį€²įŠ į€˜į€šį€ŗį€”į€į€« į€žį€Æį€¶į€øį€›į€™į€œį€²
  • While loop syntax နဲ့ į€”į€œį€Æį€•į€ŗį€œį€Æį€•į€ŗį€•į€Æį€¶
  • While vs For loops - į€˜į€šį€ŗį€”į€į€»į€­į€”į€ŗ į€˜į€¬į€žį€Æį€¶į€øį€›į€™į€œį€²
  • Do-While loop - į€”į€”į€Šį€ŗį€øį€†į€Æį€¶į€ø တစ်ကြိမ် run į€›į€™į€šį€·į€ŗ loop
  • Infinite loops - į€˜į€¬į€€į€¼į€±į€¬į€„į€·į€ŗ į€–į€¼į€…į€ŗį€œį€²įŠ į€˜į€šį€ŗį€œį€­į€Æ į€›į€¾į€±į€¬į€„į€ŗį€›į€™į€œį€²
  • Loop control statements (break & continue)
  • Input validation နဲ့ menu systems
  • Real-world practical examples

šŸ“– While Loop ဆိုတာ į€˜į€¬į€œį€²?

While loop ဆိုတာ condition true į€–į€¼į€…į€ŗį€žį€›į€½į€±į€· code block ကို ထပ်ခါထပ်ခါ execute į€œį€Æį€•į€ŗį€į€²į€· loop တစ်မျိုးပါ။ For loop į€œį€­į€Æ iterations နရေနတွက် į€žį€­į€…į€›į€¬ į€™į€œį€­į€Æį€˜į€°į€ø - condition false ဖြစ်တဲ့နထိ run į€”į€±į€™į€šį€ŗį‹

į€”į€±į€·į€…į€‰į€ŗį€˜į€į€™į€¾į€¬ ငပမာများ:

  • į€™į€­į€Æį€øį€›į€½į€¬į€”į€±į€žį€›į€½į€±į€· နိမ်မှာ နေပါ (condition: မိုးရွာနေတာ)
  • į€œį€™į€ŗį€ø į€›į€¾į€„į€ŗį€øį€”į€±į€žį€›į€½į€±į€· မောင်းပါ (condition: į€œį€™į€ŗį€øį€›į€¾į€„į€ŗį€øį€į€¬)
  • Password į€™į€¾į€¬į€øį€”į€±į€žį€›į€½į€±į€· ထပ်မေးပါ (condition: password မှန်/မမှန်)
  • Balance į€™į€œį€Æį€¶į€œį€±į€¬į€€į€ŗį€žį€›į€½į€±į€· į€„į€½į€±į€‘į€Æį€į€ŗį€œį€­į€Æį€· į€™į€›į€˜į€°į€ø (condition: balance check)

į€”į€²į€·į€’į€®į€œį€­į€Æ scenarios တွေမှာ while loop က perfect!

For vs While - နဓိက ခြားနားချက်

Aspect For Loop While Loop
į€”į€žį€Æį€¶į€øį€•į€¼į€Æį€›į€”į€ŗ Iterations į€žį€­į€į€»į€„į€ŗį€į€²į€·į€”į€į€« Condition နပေါ် į€™į€°į€į€Šį€ŗį€į€²į€·į€”į€į€«
Structure for (init; condition; increment) while (condition)
Best for Arrays, counting, known iterations User input, validation, unknown iterations
Example Print 1 to 100 Keep asking until password correct

šŸ”¹ Basic While Loop Syntax

While loop ရဲ့ basic structure:

Java
while (condition) {
    // condition က true į€–į€¼į€…į€ŗį€žį€›į€½į€±į€· run į€™į€šį€ŗ
    statements;
    // condition ကို update į€œį€Æį€•į€ŗį€–į€­į€Æį€· မမေ့ပါနဲ့!
}

နရေးကြီးတဲ့ နချက်များ:

  • Condition check: Loop body run မီ condition ကို į€…į€…į€ŗį€į€šį€ŗ (pre-check)
  • Update variable: Loop body ထဲမှာ condition ကို update į€œį€Æį€•į€ŗį€›į€™į€šį€ŗ (infinite loop ဖြစ်မှာ į€™į€Ÿį€Æį€į€ŗį€›į€„į€ŗ)
  • Zero iterations: Initial condition က false ဆိုရင် တစ်ကြိမ်မှ မ run į€˜į€°į€ø
  • Boolean condition: Condition က boolean expression į€–į€¼į€…į€ŗį€›į€™į€šį€ŗ (true/false)

Flow Chart

1. Check condition → true?
   ā”œā”€ Yes: Execute loop body
   │         ↓
   │   Update variables
   │         ↓
   │   Go back to step 1
   │
   └─ No: Exit loop, continue program
                    

šŸ”¹ Simple Example: Count to 10

While loop နဲ့ 1 ကနေ 10 နထိ ရေတွက်ခြင်း:

Java
public class WhileCount {
    public static void main(String[] args) {
        int i = 1;  // Initialize
        
        while (i <= 10) {  // Condition
            System.out.println(i);
            i++;  // Update (နရေးကြီး!)
        }
        
        System.out.println("Done!");
    }
}
Output:
1
2
3
4
5
6
7
8
9
10
Done!

For loop နဲ့ į€”į€¾į€­į€Æį€„į€ŗį€øį€šį€¾į€‰į€ŗį€›į€„į€ŗ:

// While loop
int i = 1;
while (i <= 10) {
    System.out.println(i);
    i++;
}

// For loop (same result)
for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}

// For loop က တိုပြီး clean į€•į€­į€Æį€–į€¼į€…į€ŗį€į€šį€ŗ known iterations နတွက်!

šŸ”¹ Input Validation - While Loop ရဲ့ နင်နား!

User က valid input į€™į€‘į€Šį€·į€ŗį€žį€™į€»į€¾ ထပ်မေးဖို့ while loop က perfect:

Example 1: Password Validation

Java
import java.util.Scanner;

public class PasswordCheck {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String correctPassword = "java123";
        String userInput = "";
        int attempts = 0;
        int maxAttempts = 3;
        
        System.out.println("=== Password Login System ===");
        
        while (!userInput.equals(correctPassword) && attempts < maxAttempts) {
            System.out.print("Enter password: ");
            userInput = scanner.nextLine();
            attempts++;
            
            if (!userInput.equals(correctPassword)) {
                int remaining = maxAttempts - attempts;
                if (remaining > 0) {
                    System.out.println("āŒ Wrong password! " + remaining + " attempts left.");
                } else {
                    System.out.println("āŒ Account locked! Too many failed attempts.");
                }
            }
        }
        
        if (userInput.equals(correctPassword)) {
            System.out.println("āœ“ Login successful! Welcome!");
        }
        
        scanner.close();
    }
}
Sample Output:
=== Password Login System ===
Enter password: abc123
āŒ Wrong password! 2 attempts left.
Enter password: test
āŒ Wrong password! 1 attempts left.
Enter password: java123
āœ“ Login successful! Welcome!

Example 2: Age Validation

Java
import java.util.Scanner;

public class AgeValidation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int age = -1;  // Invalid initial value
        
        System.out.println("Enter your age (1-120):");
        
        while (age < 1 || age > 120) {
            System.out.print("Age: ");
            
            if (scanner.hasNextInt()) {
                age = scanner.nextInt();
                
                if (age < 1 || age > 120) {
                    System.out.println("Invalid age! Please enter between 1 and 120.");
                }
            } else {
                System.out.println("Please enter a valid number!");
                scanner.next();  // Clear invalid input
            }
        }
        
        System.out.println("Thank you! Your age: " + age);
        scanner.close();
    }
}

šŸ”¹ Menu-Driven Programs

Menu systems မှာ while loop က နရမ်း į€žį€Æį€¶į€øį€į€šį€ŗ - user က exit မရွေးမချင်း ထပ်ခါထပ်ခါ menu į€•į€¼į€”į€±į€į€šį€ŗ:

Java
import java.util.Scanner;

public class CalculatorMenu {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int choice = 0;
        
        while (choice != 5) {
            System.out.println("\n=== Simple Calculator ===");
            System.out.println("1. Addition");
            System.out.println("2. Subtraction");
            System.out.println("3. Multiplication");
            System.out.println("4. Division");
            System.out.println("5. Exit");
            System.out.print("Enter choice (1-5): ");
            
            choice = scanner.nextInt();
            
            if (choice >= 1 && choice <= 4) {
                System.out.print("Enter first number: ");
                double num1 = scanner.nextDouble();
                System.out.print("Enter second number: ");
                double num2 = scanner.nextDouble();
                double result = 0;
                
                switch (choice) {
                    case 1:
                        result = num1 + num2;
                        System.out.println("Result: " + num1 + " + " + num2 + " = " + result);
                        break;
                    case 2:
                        result = num1 - num2;
                        System.out.println("Result: " + num1 + " - " + num2 + " = " + result);
                        break;
                    case 3:
                        result = num1 * num2;
                        System.out.println("Result: " + num1 + " Ɨ " + num2 + " = " + result);
                        break;
                    case 4:
                        if (num2 != 0) {
                            result = num1 / num2;
                            System.out.println("Result: " + num1 + " Ć· " + num2 + " = " + result);
                        } else {
                            System.out.println("Error: Cannot divide by zero!");
                        }
                        break;
                }
            } else if (choice == 5) {
                System.out.println("Thank you for using calculator! Goodbye!");
            } else {
                System.out.println("Invalid choice! Please select 1-5.");
            }
        }
        
        scanner.close();
    }
}
Sample Output:
=== Simple Calculator ===
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter choice (1-5): 1
Enter first number: 10
Enter second number: 5
Result: 10.0 + 5.0 = 15.0

=== Simple Calculator ===
1. Addition
...
Enter choice (1-5): 5
Thank you for using calculator! Goodbye!

šŸ”¹ Do-While Loop

Do-while loop က while loop နဲ့ į€†į€„į€ŗį€į€šį€ŗįŠ į€’į€«į€•į€±į€™į€šį€·į€ŗ condition ကို နဆုံးမှာ į€…į€…į€ŗį€į€šį€ŗį‹ į€†į€­į€Æį€œį€­į€Æį€į€¬į€€ į€”į€”į€Šį€ŗį€øį€†į€Æį€¶į€ø တစ်ကြိမ် run į€™į€šį€ŗ!

Java Syntax
do {
    // Code ကို နရင် run į€į€šį€ŗ
    statements;
} while (condition);  // နောက်မှ condition į€…į€…į€ŗį€į€šį€ŗ

While vs Do-While:

  • While: Condition နရင်စစ် → true ဖြစ်မှ run (0 or more times)
  • Do-While: နရင် run → နောက် condition စစ် (1 or more times)

Example: Menu (Must Show At Least Once)

Java
import java.util.Scanner;

public class DoWhileMenu {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String response;
        
        do {
            System.out.println("\n=== Welcome to Our Service ===");
            System.out.println("We're here to help you!");
            System.out.println("Have a great day!");
            
            System.out.print("\nDo you want to see this again? (yes/no): ");
            response = scanner.nextLine().toLowerCase();
            
        } while (response.equals("yes"));
        
        System.out.println("Goodbye!");
        scanner.close();
    }
}

Comparison Example

Java
// While loop
int x = 10;
while (x < 5) {
    System.out.println("This never prints!");  // į€˜į€¬į€™į€¾ į€™į€‘į€½į€€į€ŗį€˜į€°į€ø
}

// Do-While loop
int y = 10;
do {
    System.out.println("This prints once!");  // တစ်ကြိမ် į€‘į€½į€€į€ŗį€į€šį€ŗ
} while (y < 5);

šŸ”¹ Infinite Loops - į€”į€”į€¹į€į€›į€¬į€šį€ŗ!

Infinite loop ဆိုတာ condition က į€˜į€šį€ŗį€į€±į€¬į€·į€™į€¾ false į€™į€–į€¼į€…į€ŗį€œį€­į€Æį€· loop က နဆုံးမရှိ run နေတဲ့ နခြေနနေပါ:

āŒ Common Infinite Loop Mistakes

WRONG!
// Mistake 1: Forgot to update
int i = 1;
while (i <= 10) {
    System.out.println(i);
    // i++ į€‘į€Šį€·į€ŗį€–į€­į€Æį€· į€™į€±į€·į€žį€½į€¬į€øį€į€šį€ŗ!
}

// Mistake 2: Wrong update direction
int j = 1;
while (j <= 10) {
    System.out.println(j);
    j--;  // Decreasing instead of increasing!
}

// Mistake 3: Always true condition
while (true) {
    System.out.println("Forever!");
    // No break statement!
}

// Mistake 4: Wrong comparison
int count = 0;
while (count != 10) {
    System.out.println(count);
    count += 2;  // 0,2,4,6,8,10,12... į€˜į€šį€ŗį€į€±į€¬į€·į€™į€¾ 10 į€™į€į€°į€˜į€°į€ø!
}

āœ… How to Avoid Infinite Loops

  • Always update: Loop variable ကို loop body ထဲမှာ update į€œį€Æį€•į€ŗį€•į€«
  • Check direction: Increment/decrement က condition နဲ့ į€Šį€®į€›į€™į€šį€ŗ
  • Use break: Intentional infinite loop မှာ break condition į€‘į€Šį€·į€ŗį€•į€«
  • Test carefully: Small values နဲ့ test į€œį€Æį€•į€ŗį€•į€« (100 နစား 5)
  • Add counter: Safety counter į€‘į€Šį€·į€ŗį€•į€¼į€®į€ø maximum iterations limit į€œį€Æį€•į€ŗį€•į€«

Intentional Infinite Loop (With Break)

Java - Correct Usage
import java.util.Scanner;

public class ServerSimulation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Server က ပိတ်ဖို့ command į€™į€›į€žį€™į€»į€¾ run į€”į€±į€™į€šį€ŗ
        while (true) {
            System.out.print("Server> ");
            String command = scanner.nextLine();
            
            if (command.equals("exit")) {
                System.out.println("Shutting down server...");
                break;  // Exit the infinite loop
            }
            
            System.out.println("Processing: " + command);
        }
        
        scanner.close();
    }
}

šŸ”¹ Loop Control: Break & Continue

Break Statement

Loop ကနေ ချက်ချင်း ထွက်ဖို့:

Java
// Example: Find first even number
int[] numbers = {1, 3, 5, 7, 8, 9, 11};
int i = 0;

while (i < numbers.length) {
    if (numbers[i] % 2 == 0) {
        System.out.println("First even number: " + numbers[i]);
        break;  // Found it, exit loop
    }
    i++;
}

// Output: First even number: 8

Continue Statement

Current iteration ကို skip į€œį€Æį€•į€ŗį€•į€¼į€®į€ø next iteration į€žį€½į€¬į€øį€–į€­į€Æį€·:

Java
// Example: Print only odd numbers
int i = 1;

while (i <= 10) {
    if (i % 2 == 0) {
        i++;
        continue;  // Skip even numbers
    }
    
    System.out.println(i);  // Only odd numbers print
    i++;
}

// Output: 1, 3, 5, 7, 9

Break vs Continue:

  • break: Loop ကနေ į€œį€Æį€¶į€øį€į€‘į€½į€€į€ŗį€žį€½į€¬į€øį€į€šį€ŗ
  • continue: Current iteration ကို skip į€œį€Æį€•į€ŗį€•į€¼į€®į€ø next iteration ကို į€†į€€į€ŗį€œį€Æį€•į€ŗį€į€šį€ŗ

šŸ’» Complete Example: Number Guessing Game

While loop, break, continue į€”į€¬į€øį€œį€Æį€¶į€ø ပေါင်းစပ်ထားတဲ့ complete game:

Java
import java.util.Scanner;
import java.util.Random;

public class NumberGuessingGame {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();
        
        System.out.println("=== Number Guessing Game ===");
        System.out.println("I'm thinking of a number between 1 and 100.");
        
        int targetNumber = random.nextInt(100) + 1;
        int attempts = 0;
        int maxAttempts = 7;
        boolean hasWon = false;
        
        while (attempts < maxAttempts) {
            int remaining = maxAttempts - attempts;
            System.out.println("\nAttempts remaining: " + remaining);
            System.out.print("Enter your guess: ");
            
            // Input validation
            if (!scanner.hasNextInt()) {
                System.out.println("āŒ Invalid input! Please enter a number.");
                scanner.next();  // Clear bad input
                continue;  // Skip this iteration
            }
            
            int guess = scanner.nextInt();
            attempts++;
            
            // Check if out of range
            if (guess < 1 || guess > 100) {
                System.out.println("āŒ Please guess between 1 and 100!");
                attempts--;  // Don't count this attempt
                continue;
            }
            
            // Check the guess
            if (guess == targetNumber) {
                hasWon = true;
                System.out.println("\nšŸŽ‰ Congratulations! You won!");
                System.out.println("The number was: " + targetNumber);
                System.out.println("You guessed it in " + attempts + " attempts!");
                break;  // Exit the loop
                
            } else if (guess < targetNumber) {
                int difference = targetNumber - guess;
                
                if (difference <= 5) {
                    System.out.println("šŸ”„ Very close! Too low!");
                } else if (difference <= 15) {
                    System.out.println("šŸ“ˆ Too low!");
                } else {
                    System.out.println("ā¬†ļø Way too low!");
                }
                
            } else {
                int difference = guess - targetNumber;
                
                if (difference <= 5) {
                    System.out.println("šŸ”„ Very close! Too high!");
                } else if (difference <= 15) {
                    System.out.println("šŸ“‰ Too high!");
                } else {
                    System.out.println("ā¬‡ļø Way too high!");
                }
            }
        }
        
        if (!hasWon) {
            System.out.println("\n😢 Game Over! You ran out of attempts.");
            System.out.println("The number was: " + targetNumber);
        }
        
        System.out.println("\nThanks for playing!");
        scanner.close();
    }
}
Sample Output:
=== Number Guessing Game ===
I'm thinking of a number between 1 and 100.

Attempts remaining: 7
Enter your guess: 50
šŸ“‰ Too high!

Attempts remaining: 6
Enter your guess: 25
šŸ“ˆ Too low!

Attempts remaining: 5
Enter your guess: 37
šŸ”„ Very close! Too low!

Attempts remaining: 4
Enter your guess: 40
šŸŽ‰ Congratulations! You won!
The number was: 40
You guessed it in 4 attempts!

Thanks for playing!

šŸ’» Advanced Example: ATM Banking System

Real-world scenario - ATM machine simulation:

Java
import java.util.Scanner;

public class ATMSystem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Account data
        String accountName = "Aung Aung";
        int pin = 1234;
        double balance = 50000;
        boolean isAuthenticated = false;
        int loginAttempts = 0;
        int maxLoginAttempts = 3;
        
        System.out.println("=== Welcome to A Coder Bank ATM ===");
        
        // PIN verification
        while (!isAuthenticated && loginAttempts < maxLoginAttempts) {
            System.out.print("Enter your PIN: ");
            int userPin = scanner.nextInt();
            loginAttempts++;
            
            if (userPin == pin) {
                isAuthenticated = true;
                System.out.println("āœ“ Login successful!");
            } else {
                int remaining = maxLoginAttempts - loginAttempts;
                if (remaining > 0) {
                    System.out.println("āŒ Incorrect PIN! " + remaining + " attempts left.");
                } else {
                    System.out.println("āŒ Card blocked! Too many failed attempts.");
                }
            }
        }
        
        // Main menu (if authenticated)
        if (isAuthenticated) {
            int choice = 0;
            
            while (choice != 4) {
                System.out.println("\n=== Main Menu ===");
                System.out.println("Account: " + accountName);
                System.out.println("1. Check Balance");
                System.out.println("2. Deposit");
                System.out.println("3. Withdraw");
                System.out.println("4. Exit");
                System.out.print("Enter choice (1-4): ");
                
                choice = scanner.nextInt();
                
                switch (choice) {
                    case 1:
                        // Check balance
                        System.out.println("\n=== Balance Inquiry ===");
                        System.out.println("Current Balance: " + balance + " Kyats");
                        break;
                        
                    case 2:
                        // Deposit
                        System.out.println("\n=== Deposit ===");
                        System.out.print("Enter amount to deposit: ");
                        double depositAmount = scanner.nextDouble();
                        
                        if (depositAmount > 0 && depositAmount <= 1000000) {
                            balance += depositAmount;
                            System.out.println("āœ“ Deposit successful!");
                            System.out.println("Deposited: " + depositAmount + " Kyats");
                            System.out.println("New Balance: " + balance + " Kyats");
                        } else {
                            System.out.println("āŒ Invalid amount! (Max: 1,000,000 Kyats)");
                        }
                        break;
                        
                    case 3:
                        // Withdraw
                        System.out.println("\n=== Withdrawal ===");
                        System.out.print("Enter amount to withdraw: ");
                        double withdrawAmount = scanner.nextDouble();
                        
                        if (withdrawAmount <= 0) {
                            System.out.println("āŒ Invalid amount!");
                        } else if (withdrawAmount > balance) {
                            System.out.println("āŒ Insufficient balance!");
                            System.out.println("Available: " + balance + " Kyats");
                        } else if (withdrawAmount > 500000) {
                            System.out.println("āŒ Daily withdrawal limit: 500,000 Kyats");
                        } else {
                            balance -= withdrawAmount;
                            System.out.println("āœ“ Withdrawal successful!");
                            System.out.println("Withdrawn: " + withdrawAmount + " Kyats");
                            System.out.println("Remaining Balance: " + balance + " Kyats");
                            
                            // Dispense money simulation
                            System.out.println("\nDispensing money...");
                            int[] notes = {50000, 10000, 5000, 1000};
                            double remaining = withdrawAmount;
                            
                            for (int note : notes) {
                                if (remaining >= note) {
                                    int count = (int)(remaining / note);
                                    System.out.println(note + " Kyats Ɨ " + count);
                                    remaining = remaining % note;
                                }
                            }
                        }
                        break;
                        
                    case 4:
                        System.out.println("\n=== Thank You ===");
                        System.out.println("Please take your card.");
                        System.out.println("Have a nice day!");
                        break;
                        
                    default:
                        System.out.println("āŒ Invalid choice! Please select 1-4.");
                }
            }
        }
        
        scanner.close();
    }
}
Sample Output:
=== Welcome to A Coder Bank ATM ===
Enter your PIN: 1234
āœ“ Login successful!

=== Main Menu ===
Account: Aung Aung
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Enter choice (1-4): 3

=== Withdrawal ===
Enter amount to withdraw: 75000
āœ“ Withdrawal successful!
Withdrawn: 75000.0 Kyats
Remaining Balance: -25000.0 Kyats

Dispensing money...
50000 Kyats Ɨ 1
10000 Kyats Ɨ 2
5000 Kyats Ɨ 1

=== Main Menu ===
...

šŸ”¹ Common While Loop Patterns

Pattern 1: Sentinel-Controlled Loop

Special value (sentinel) ရောက်တဲ့နထိ run:

Java
Scanner scanner = new Scanner(System.in);
int num;

System.out.println("Enter numbers (0 to stop):");

while ((num = scanner.nextInt()) != 0) {
    System.out.println("You entered: " + num);
}

System.out.println("Done!");

Pattern 2: Flag-Controlled Loop

Boolean flag į€žį€Æį€¶į€øį€•į€¼į€®į€ø control:

Java
boolean keepRunning = true;

while (keepRunning) {
    // Do something
    
    if (someCondition) {
        keepRunning = false;  // Stop the loop
    }
}

Pattern 3: Counter-Controlled (Known Max)

Maximum iterations ရှိတဲ့ validation:

Java
int attempts = 0;
int maxAttempts = 5;
boolean success = false;

while (!success && attempts < maxAttempts) {
    // Try something
    attempts++;
    
    if (successfulOperation) {
        success = true;
    }
}

šŸŽÆ နဓိက į€™į€¾į€į€ŗį€žį€¬į€øį€›į€™į€Šį€·į€ŗ နချက်များ

  • While loop: Condition true į€–į€¼į€…į€ŗį€žį€›į€½į€±į€· run į€į€šį€ŗ (0 or more times)
  • Do-while loop: နရင် run, နောက် condition စစ် (1 or more times)
  • Use while when: Iterations į€™į€žį€­, condition-based, user input validation
  • Use for when: Iterations į€žį€­, counting, arrays
  • Always update: Loop variable ကို update į€œį€Æį€•į€ŗį€–į€­į€Æį€· မမေ့ပါနဲ့ (infinite loop į€–į€¼į€…į€ŗį€™į€šį€ŗ)
  • Break: Loop ကနေ į€œį€Æį€¶į€øį€į€‘į€½į€€į€ŗį€–į€­į€Æį€·
  • Continue: Current iteration skip į€œį€Æį€•į€ŗį€–į€­į€Æį€·
  • Input validation: While loop က perfect (valid input į€™į€›į€žį€™į€»į€¾ ထပ်မေး)
  • Menu systems: Do-while į€žį€Æį€¶į€øį€›į€„į€ŗ menu ကို į€”į€”į€Šį€ŗį€øį€†į€Æį€¶į€ø တစ်ကြိမ် į€•į€¼į€į€šį€ŗ
  • Infinite loops: Testing နဲ့ safety counters į€žį€Æį€¶į€øį€•į€¼į€®į€ø ရှောင်ပါ
  • Boolean flags: Complex conditions နတွက် boolean variables į€žį€Æį€¶į€øį€•į€«

āœļø Practice Exercise

Exercise: Factorial Calculator

While loop į€žį€Æį€¶į€øį€•į€¼į€®į€ø factorial တွက်တဲ့ program ရေးပါ:

  • User ကနေ positive number တစ်ခု input į€šį€°į€•į€«
  • Factorial တွက်ပါ (5! = 5 Ɨ 4 Ɨ 3 Ɨ 2 Ɨ 1 = 120)
  • Input validation į€œį€Æį€•į€ŗį€•į€« (negative numbers reject)
  • User က "exit" į€œį€­į€Æį€· ရိုက်မှ ရပ်ပါ

Example:

Enter a number (or 'exit' to quit): 5
5! = 120

Enter a number (or 'exit' to quit): 6
6! = 720

Enter a number (or 'exit' to quit): exit
Goodbye!
šŸ’” Solution į€€į€¼į€Šį€·į€ŗį€›į€”į€ŗ (Try į€œį€Æį€•į€ŗį€•į€¼į€®į€øį€™į€¾ į€€į€¼į€Šį€·į€ŗį€•į€«)
Java
import java.util.Scanner;

public class FactorialCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = "";
        
        System.out.println("=== Factorial Calculator ===");
        
        while (!input.equals("exit")) {
            System.out.print("Enter a number (or 'exit' to quit): ");
            input = scanner.nextLine();
            
            if (input.equals("exit")) {
                System.out.println("Goodbye!");
                break;
            }
            
            try {
                int n = Integer.parseInt(input);
                
                if (n < 0) {
                    System.out.println("Error: Please enter a positive number!");
                    continue;
                }
                
                long factorial = 1;
                int i = 1;
                
                while (i <= n) {
                    factorial *= i;
                    i++;
                }
                
                System.out.println(n + "! = " + factorial);
                
            } catch (NumberFormatException e) {
                System.out.println("Error: Invalid input!");
            }
            
            System.out.println();
        }
        
        scanner.close();
    }
}

šŸ“ Quick Quiz

Question 1: ဒီ while loop က į€˜į€šį€ŗį€”į€¾į€…į€ŗį€€į€¼į€­į€™į€ŗ run į€™į€œį€²?

int x = 5;
while (x > 3) {
    System.out.println(x);
    x--;
}

Question 2: Do-while loop နဲ့ while loop ရဲ့ နဓိက ခြားနားချက်က į€˜į€¬į€œį€²?

Question 3: į€˜į€šį€ŗ scenario မှာ while loop က for loop ထက် į€•į€­į€Æį€€į€±į€¬į€„į€ŗį€øį€œį€²?

šŸŽ‰ Congratulations!

Module 3: Control Flow ပြီးပါပြီ!

į€žį€„į€ŗ į€žį€„į€ŗį€šį€°į€•į€¼į€®į€øį€žį€¬į€ø နရာများ:

  • āœ… Lesson 9: If-Else Statements
  • āœ… Lesson 10: Switch Statements
  • āœ… Lesson 11: For Loops
  • āœ… Lesson 12: While Loops

Course Progress: 50% Complete!
12 of 24 lessons finished!

Next: Module 4 - Methods šŸš€