Module 3 - Lesson 11

For Loops: Mastering Repetition in Java

Code ကို အကြိမ်ကြိမ် ထပ်ခါထပ်ခါ run ချင်ရင် loops တွေ သုံးရတယ်။ For loop က အသုံးများဆုံး loop type ဖြစ်ပြီး patterns, arrays, counting လုပ်ဖို့ perfect ပါ။

⏱️ 50 minutes 📚 Intermediate 🔄 Repetition Power

🎯 သင် သင်ယူမည့် အရာများ

ဒီ lesson မှာ သင် သင်ယူမည့် အရာများ:

  • Loop ဆိုတာ ဘာလဲ၊ ဘာကြောင့် လိုအပ်လဲ
  • For loop ရဲ့ syntax နဲ့ components (initialization, condition, increment)
  • Counting loops - numbers တွေ ရေတွက်ခြင်း
  • Arrays နဲ့ for loops တွေ တွဲသုံးခြင်း
  • Nested for loops - loop ထဲမှာ loop
  • Patterns နဲ့ multiplication tables ဆွဲခြင်း
  • Enhanced for loop (for-each loop)
  • Common mistakes နဲ့ best practices

📖 Loops ဆိုတာ ဘာလဲ?

Loop ဆိုတာ code block တစ်ခုကို အကြိမ်ကြိမ် ထပ်တလဲလဲ execute လုပ်နိုင်တဲ့ programming construct ပါ။ တူညီတဲ့ code ကို အကြိမ်များများ copy-paste လုပ်စရာ မလိုတော့ဘူး။

နေ့စဉ်ဘဝမှာ ဥပမာများ:

  • 1 ကနေ 100 အထိ ရေတွက်ခြင်း
  • Student စာရင်း 50 ကောင် print ခြင်း
  • Multiplication table (စားပွဲ) ဆွဲခြင်း
  • Pattern တွေ ဆွဲခြင်း (stars, pyramids)
  • Array/List ထဲက items တွေ ထုတ်ကြည့်ခြင်း

Loop မသုံးရင် code က အရမ်းရှည်သွားမယ်!

Without Loop (BAD!)

Java - Repetitive Code
System.out.println("Hello 1");
System.out.println("Hello 2");
System.out.println("Hello 3");
System.out.println("Hello 4");
System.out.println("Hello 5");
// 100 times ဆိုရင်?? 😱

With For Loop (GOOD!)

Java - Using Loop
for (int i = 1; i <= 100; i++) {
    System.out.println("Hello " + i);
}
// Clean, efficient, scalable! ✨

🔹 For Loop Syntax

For loop ရဲ့ basic structure:

Java
for (initialization; condition; increment/decrement) {
    // Loop body - ဒီ code က ထပ်ခါထပ်ခါ run မယ်
    statements;
}

Three Components (သုံးပိုင်း):

  1. Initialization: Loop variable ကို ပထမ တစ်ကြိမ် set လုပ်တယ် (တစ်ခါပဲ run)
  2. Condition: Loop ဆက် run မလား စစ်တယ် (အစကနေ အဆုံး အကြိမ်တိုင်း စစ်တယ်)
  3. Increment/Decrement: Loop variable ကို update လုပ်တယ် (iteration တစ်ခု ပြီးတိုင်း)

Flow Chart

1. Initialization → i = 1
2. Condition check → i <= 5? (Yes)
3. Execute body → Print
4. Increment → i++
5. Condition check → i <= 5? (Yes)
6. Execute body → Print
7. Increment → i++
... repeat until condition is false
                    

🔹 Simple Example: Count 1 to 10

1 ကနေ 10 အထိ ရေတွက်ခြင်း:

Java
public class CountToTen {
    public static void main(String[] args) {
        System.out.println("Counting from 1 to 10:");
        
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
        
        System.out.println("Done!");
    }
}
Output:
Counting from 1 to 10:
1
2
3
4
5
6
7
8
9
10
Done!

Step by Step:

  • int i = 1 → i ကို 1 နှ့ စတယ် (initialization)
  • i <= 10 → i က 10 ထက် နည်းလား တူလား စစ်တယ် (condition)
  • i++ → i ကို တစ်ခု တိုးတယ် (increment)
  • i = 11 ဖြစ်တော့ condition false ဖြစ်ပြီး loop ရပ်တယ်

🔹 Increment & Decrement Variations

Counting Up (အတိုးရေတွက်ခြင်း)

Java
// By 1: 1, 2, 3, 4, 5
for (int i = 1; i <= 5; i++) {
    System.out.print(i + " ");
}

// By 2: 0, 2, 4, 6, 8, 10
for (int i = 0; i <= 10; i += 2) {
    System.out.print(i + " ");
}

// By 5: 5, 10, 15, 20, 25
for (int i = 5; i <= 25; i += 5) {
    System.out.print(i + " ");
}

Counting Down (အဆင်းရေတွက်ခြင်း)

Java
// Countdown: 10, 9, 8, ..., 1, 0
for (int i = 10; i >= 0; i--) {
    System.out.print(i + " ");
    if (i == 0) {
        System.out.println("Blast off! 🚀");
    }
}
Output:
10 9 8 7 6 5 4 3 2 1 0 Blast off! 🚀

🔹 Practical Example: Sum of Numbers

1 ကနေ 100 အထိ ပေါင်းခြင်း:

Java
public class SumNumbers {
    public static void main(String[] args) {
        int sum = 0;
        
        for (int i = 1; i <= 100; i++) {
            sum = sum + i;  // or sum += i
        }
        
        System.out.println("Sum of 1 to 100 = " + sum);
    }
}
Output:
Sum of 1 to 100 = 5050

How it works:

Iteration 1: sum = 0 + 1 = 1
Iteration 2: sum = 1 + 2 = 3
Iteration 3: sum = 3 + 3 = 6
Iteration 4: sum = 6 + 4 = 10
...
Iteration 100: sum = 4950 + 100 = 5050
                    

🔹 Arrays with For Loops

For loop က array elements တွေကို access လုပ်ဖို့ perfect:

Java
public class ArrayLoop {
    public static void main(String[] args) {
        String[] cities = {"Yangon", "Mandalay", "Naypyidaw", "Bago", "Mawlamyine"};
        
        System.out.println("Cities in Myanmar:");
        
        // Using index
        for (int i = 0; i < cities.length; i++) {
            System.out.println((i + 1) + ". " + cities[i]);
        }
        
        System.out.println("\nTotal cities: " + cities.length);
    }
}
Output:
Cities in Myanmar:
1. Yangon
2. Mandalay
3. Naypyidaw
4. Bago
5. Mawlamyine

Total cities: 5

⚠️ Array Index:

  • Arrays က 0 ကနေ စတယ်: index 0, 1, 2, 3, 4
  • Last index = length - 1
  • Condition: i < cities.length (not <=)< /li>
  • i <= cities.length ဆိုရင် ArrayIndexOutOfBoundsException ရမယ်

🔹 Enhanced For Loop (For-Each)

Array/Collection items တွေကို ပိုလွယ်အောင် loop လုပ်ဖို့:

Java
// Traditional for loop
for (int i = 0; i < cities.length; i++) {
    System.out.println(cities[i]);
}

// Enhanced for loop (for-each)
for (String city : cities) {
    System.out.println(city);
}

Example: Calculate Average

Java
public class AverageScore {
    public static void main(String[] args) {
        int[] scores = {85, 92, 78, 90, 88};
        int sum = 0;
        
        // Using enhanced for loop
        for (int score : scores) {
            sum += score;
        }
        
        double average = (double) sum / scores.length;
        
        System.out.println("Total scores: " + sum);
        System.out.println("Average: " + average);
    }
}
Output:
Total scores: 433
Average: 86.6

For-Each Loop:

  • Syntax: for (type variable : array)
  • Index မလိုတဲ့အခါ သုံးတယ်
  • Code က ပိုရှင်းလင်းတယ်
  • Modification လုပ်လို့ မရဘူး (read-only)
  • Forward direction ပဲ loop လုပ်တယ်

🔹 Nested For Loops (Loop ထဲမှာ Loop)

Loop တစ်ခုထဲမှာ နောက် loop တစ်ခု ထည့်ခြင်း:

Example 1: Multiplication Table

Java
public class MultiplicationTable {
    public static void main(String[] args) {
        System.out.println("=== Multiplication Table (5x5) ===\n");
        
        // Outer loop: rows
        for (int i = 1; i <= 5; i++) {
            // Inner loop: columns
            for (int j = 1; j <= 5; j++) {
                System.out.print((i * j) + "\t");
            }
            System.out.println();  // New line after each row
        }
    }
}
Output:
=== Multiplication Table (5x5) ===

1	2	3	4	5	
2	4	6	8	10	
3	6	9	12	15	
4	8	12	16	20	
5	10	15	20	25

Example 2: Star Patterns

Java
public class StarPatterns {
    public static void main(String[] args) {
        int rows = 5;
        
        System.out.println("Pattern 1: Right Triangle");
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
        
        System.out.println("\nPattern 2: Inverted Triangle");
        for (int i = rows; i >= 1; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}
Output:
Pattern 1: Right Triangle
* 
* * 
* * * 
* * * * 
* * * * * 

Pattern 2: Inverted Triangle
* * * * * 
* * * * 
* * * 
* * 
*

Nested Loop အလုပ်လုပ်ပုံ:

  • Outer loop က တစ်ကြိမ် run တိုင်း inner loop က အပြည့် run တယ်
  • Outer loop iteration 1 → Inner loop 1-5 ကြိမ်
  • Outer loop iteration 2 → Inner loop 1-5 ကြိမ်
  • Total iterations = outer × inner (5 × 5 = 25)

💻 Complete Example: Grade Analyzer

Students များ၏ scores များကို analyze လုပ်ခြင်း:

Java
public class GradeAnalyzer {
    public static void main(String[] args) {
        String[] students = {"Aung Aung", "Su Su", "Ko Ko", "Mya Mya", "Zaw Zaw"};
        int[] scores = {85, 92, 78, 95, 88};
        
        System.out.println("=== Grade Analysis Report ===\n");
        
        // Display individual grades
        System.out.println("Student Grades:");
        for (int i = 0; i < students.length; i++) {
            String grade;
            
            if (scores[i] >= 90) {
                grade = "A";
            } else if (scores[i] >= 80) {
                grade = "B";
            } else if (scores[i] >= 70) {
                grade = "C";
            } else {
                grade = "F";
            }
            
            System.out.println((i + 1) + ". " + students[i] + ": " + 
                             scores[i] + " → Grade " + grade);
        }
        
        // Calculate statistics
        int total = 0;
        int highest = scores[0];
        int lowest = scores[0];
        String topStudent = students[0];
        
        for (int i = 0; i < scores.length; i++) {
            total += scores[i];
            
            if (scores[i] > highest) {
                highest = scores[i];
                topStudent = students[i];
            }
            
            if (scores[i] < lowest) {
                lowest = scores[i];
            }
        }
        
        double average = (double) total / scores.length;
        
        System.out.println("\n=== Statistics ===");
        System.out.println("Total Students: " + students.length);
        System.out.println("Average Score: " + average);
        System.out.println("Highest Score: " + highest + " (" + topStudent + ")");
        System.out.println("Lowest Score: " + lowest);
        
        // Count grades
        int countA = 0, countB = 0, countC = 0, countF = 0;
        
        for (int score : scores) {
            if (score >= 90) countA++;
            else if (score >= 80) countB++;
            else if (score >= 70) countC++;
            else countF++;
        }
        
        System.out.println("\n=== Grade Distribution ===");
        System.out.println("A: " + countA + " students");
        System.out.println("B: " + countB + " students");
        System.out.println("C: " + countC + " students");
        System.out.println("F: " + countF + " students");
    }
}
Output:
=== Grade Analysis Report ===

Student Grades:
1. Aung Aung: 85 → Grade B
2. Su Su: 92 → Grade A
3. Ko Ko: 78 → Grade C
4. Mya Mya: 95 → Grade A
5. Zaw Zaw: 88 → Grade B

=== Statistics ===
Total Students: 5
Average Score: 87.6
Highest Score: 95 (Mya Mya)
Lowest Score: 78

=== Grade Distribution ===
A: 2 students
B: 2 students
C: 1 students
F: 0 students

🔹 Common Mistakes & Best Practices

❌ Mistake 1: Infinite Loop

WRONG!
// Infinite loop - i never changes!
for (int i = 0; i < 10; ) {  // Missing increment
    System.out.println(i);
}

// Infinite loop - wrong increment
for (int i = 10; i > 0; i++) {  // i increases instead of decreasing
    System.out.println(i);
}

❌ Mistake 2: Off-by-One Error

WRONG!
int[] arr = {1, 2, 3, 4, 5};

// ArrayIndexOutOfBoundsException!
for (int i = 0; i <= arr.length; i++) {  // Should be i < arr.length
    System.out.println(arr[i]);
}

✅ Best Practices

  • Variable naming: i, j, k သုံးတယ် (short loops အတွက်), meaningful names သုံးပါ (index, count)
  • Array loops: i < array.length သုံးပါ (not <=)< /li>
  • Avoid modification: Loop variable ကို loop body ထဲမှာ မပြောင်းပါနဲ့
  • Use for-each: Index မလိုရင် for-each သုံးပါ (cleaner)
  • Nested loops: 2-3 levels အထိပဲ၊ များလွန်းရင် code ရှုပ်တယ်
  • Break early: လိုအပ်ရင် break သုံးပြီး loop ကနေ ထွက်ပါ

🎯 အဓိက မှတ်သားရမည့် အချက်များ

  • For loop: Code ကို အကြိမ်ကြိမ် run ဖို့ အသုံးပြုတယ်
  • Syntax: for (initialization; condition; increment) { }
  • Three parts: initialization, condition check, increment/decrement
  • Arrays: i < array.length သုံးပါ (0-based indexing)
  • Enhanced for: for (type var : array) - cleaner, read-only
  • Nested loops: Loop ထဲမှာ loop - patterns, tables အတွက်
  • Increment: i++, i+=2, i+=5 စတာတွေ သုံးလို့ရတယ်
  • Decrement: i-- သုံးပြီး countdown လုပ်လို့ရတယ်
  • Infinite loop: Increment/condition မမှန်ရင် infinite loop ဖြစ်နိုင်တယ်
  • Break: Loop ကနေ ထွက်ဖို့ break သုံးတယ်
  • Continue: Current iteration skip လုပ်ပြီး next iteration သွားတယ်

✍️ Practice Exercise

Exercise: Fibonacci Sequence

Fibonacci sequence ရဲ့ ပထမ 10 terms ကို print လုပ်ပါ:

  • Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
  • Formula: next = previous1 + previous2
  • Start with 0 and 1

Expected Output: 0 1 1 2 3 5 8 13 21 34

💡 Solution ကြည့်ရန် (Try လုပ်ပြီးမှ ကြည့်ပါ)
Java
public class FibonacciSequence {
    public static void main(String[] args) {
        int n = 10;  // Number of terms
        int first = 0, second = 1;
        
        System.out.println("First " + n + " Fibonacci numbers:");
        
        for (int i = 1; i <= n; i++) {
            System.out.print(first + " ");
            
            // Calculate next term
            int next = first + second;
            
            // Update for next iteration
            first = second;
            second = next;
        }
        
        System.out.println();
    }
}

📝 Quick Quiz

Question 1: ဒီ loop က ဘယ်နှစ်ကြိမ် run မလဲ?

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

Question 2: Array length = 10 ဆိုရင် correct loop condition က ဘာလဲ?

Question 3: Enhanced for loop (for-each) ကို ဘယ်အချိန်သုံးသင့်လဲ?