Control Flow II — Loops, break, continue, labels

লুপ — for, while, do-while, break, continue

Read: ~30 min Intermediate 5 practice problems Live code runner

1. Why Loops?

Loops repeat a block of code. Java gives you four shapes — while, do-while, classic for, and the enhanced for-each — plus break to exit early and continue to skip to the next iteration. A label lets break or continue target an outer loop.

Loop একই কাজ বারবার করায়। Java-তে চার ধরনের — while, do-while, classic for, এবং for-each। break loop থেকে বের হয়, continue পরের iteration-এ যায়। Label দিয়ে nested loop-এও নিয়ন্ত্রণ রাখা যায়।

2. while and do-while

Main.java
class Main {
    public static void main(String[] args) {
        // while: test first, body may run 0 times
        int n = 5, fact = 1;
        while (n > 1) {
            fact *= n;
            n--;
        }
        System.out.println("5! = " + fact);

        // do-while: body runs at least once, then test
        int guess = 0;
        do {
            guess++;
        } while (guess * guess < 100);
        System.out.println("smallest x with x*x >= 100 → " + guess);
    }
}
while শর্ত আগে মেলায় — condition false হলে body একবারও চলে না। do-while body অন্তত একবার চলে তারপর শর্ত দেখে — user input নেওয়ার menu loop-এ কাজে আসে।

3. Classic for — When You Know the Count

Main.java
class Main {
    public static void main(String[] args) {
        // Print 1..10, highlighting multiples of 3
        for (int i = 1; i <= 10; i++) {
            System.out.print(i);
            if (i % 3 == 0) System.out.print("*");
            System.out.print(" ");
        }
        System.out.println();

        // Counting down with step 2
        for (int i = 20; i > 0; i -= 2) System.out.print(i + " ");
        System.out.println();
    }
}
Classic for (init; cond; update) — iteration-এর সংখ্যা জানা থাকলে সবচেয়ে উপযুক্ত। Init, condition, update — তিন জায়গা এক লাইনে, পড়তে সহজ।

4. Enhanced for-each — Iterate Collections Cleanly

Main.java
import java.util.*;

class Main {
    public static void main(String[] args) {
        String[] cities = { "Dhaka", "Chattogram", "Sylhet", "Khulna" };
        for (String c : cities) System.out.println(c);

        List<Integer> nums = List.of(10, 20, 30, 40);
        long total = 0;
        for (int n : nums) total += n;
        System.out.println("sum = " + total);
    }
}
for-each (Java 5+) — array বা Collection iterate করার পরিচ্ছন্ন রূপ। কিন্তু index দরকার হলে classic for-ই ভালো। এবং iterate করার সময় Collection থেকে remove করতে চাইলে Iterator বা stream ব্যবহার করুন।

5. break and continue

Main.java
class Main {
    public static void main(String[] args) {
        // Find first multiple of 7 over 50
        for (int i = 50; i < 100; i++) {
            if (i % 7 == 0) {
                System.out.println("First: " + i);
                break;                     // exit this loop
            }
        }

        // Print only odd numbers in 1..10
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) continue;   // skip this iteration
            System.out.print(i + " ");
        }
        System.out.println();
    }
}
break — তৎক্ষণাৎ loop-এর বাইরে। continue — বর্তমান iteration বাদ দিয়ে পরেরটিতে চলে যাওয়া। দুটিই innermost loop-কে target করে — যদি না label ব্যবহার করা হয়।

6. Labeled break — Escaping Nested Loops

Main.java
class Main {
    public static void main(String[] args) {
        int[][] grid = {
            {1, 2, 3},
            {4, 5, 42},
            {7, 8, 9}
        };
        outer:                                         // label the outer loop
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[r].length; c++) {
                if (grid[r][c] == 42) {
                    System.out.println("Found 42 at " + r + "," + c);
                    break outer;                // exit BOTH loops
                }
            }
        }
    }
}
Nested loop-এ সাধারণ break শুধু ভেতরের loop থেকে বের হয়। দুটি loop একসাথে বন্ধ করতে outer loop-এ একটি label বসান, তারপর break outer; ব্যবহার করুন। Java-র কম-জানা, কিন্তু কার্যকরী feature।

7. Infinite Loops — and Exit Conditions

while(true) and for(;;) loop forever until something inside breaks them. Useful for event loops, servers, retry logic — but always build in an exit.

Main.java
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.print("> ");
            if (!sc.hasNextLine()) break;
            String line = sc.nextLine();
            if (line.equalsIgnoreCase("bye")) {
                System.out.println("See you!");
                break;
            }
            System.out.println("you said: " + line);
        }
    }
}
while(true) বা for(;;) চিরস্থায়ী loop। server, UI event loop, retry logic-এ দরকারি। কিন্তু ভেতরে অবশ্যই একটি exit শর্ত রাখুন — না হলে আপনার প্রোগ্রাম জমে যাবে।

8. Vocabulary

TermMeaningবাংলায়
IterationOne pass through a loop body.loop body-র একটি চক্র।
whileTest-then-body loop.আগে শর্ত, তারপর body।
do-whileBody-then-test; runs at least once.অন্তত একবার চলে তারপর শর্ত।
for-eachIterates an array/Iterable cleanly.Array/Collection-এর উপর পরিচ্ছন্ন loop।
breakExit the current (or labeled) loop.loop-এর বাইরে বের হওয়া।
continueSkip to next iteration.পরের iteration-এ যাওয়া।
LabelA name attached to a loop, used by break/continue.loop-কে দেওয়া নাম।

9. Practice Problems

  1. Compute the sum of all multiples of 3 or 5 below 1000 using a for loop.
    ১০০০-এর নিচে ৩ বা ৫-এর গুণিতকগুলোর যোগফল।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            long sum = 0;
            for (int i = 1; i < 1000; i++)
                if (i % 3 == 0 || i % 5 == 0) sum += i;
            System.out.println(sum);
        }
    }
  2. Print a 5-row right-triangle of * using nested for loops.
    Nested for দিয়ে ৫-সারির right-triangle।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            for (int r = 1; r <= 5; r++) {
                for (int c = 0; c < r; c++) System.out.print("* ");
                System.out.println();
            }
        }
    }
  3. Use a labeled break to stop searching a 2D array the moment you find a negative number.
    labeled break দিয়ে 2D array-তে প্রথম ঋণাত্মক মান খুঁজে বের হন।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            int[][] g = { {1,2,3}, {4,-7,9}, {8,2,6} };
            scan:
            for (int r = 0; r < g.length; r++) {
                for (int c = 0; c < g[r].length; c++) {
                    if (g[r][c] < 0) {
                        System.out.println("negative at " + r + "," + c + " = " + g[r][c]);
                        break scan;
                    }
                }
            }
        }
    }
  4. Explain in 2-3 sentences when do-while is more appropriate than while.
    কখন while-এর চেয়ে do-while বেশি উপযুক্ত?
    ✨ Show Answer (উত্তর দেখুন)

    Answer: Use do-while when the body must execute at least once before the condition can be meaningfully evaluated. The classic example is an interactive menu — you have to show the menu and read a choice before you know whether the user wanted to quit. With while, a false initial condition would skip that first pass entirely.

  5. Sum the digits of a positive integer using a while loop (hint: n % 10, then n /= 10).
    while loop দিয়ে একটি সংখ্যার digit-যোগফল।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            int n = 48729, sum = 0, original = n;
            while (n > 0) {
                sum += n % 10;
                n /= 10;
            }
            System.out.println("digit sum of " + original + " = " + sum);
        }
    }

Summary — Module 10

Four loop shapes: while, do-while, classic for, and for-each. Pick based on what you need — while for open-ended conditions, for when the count is known, for-each for collections. break exits, continue skips. Labels let you escape from nested loops. Infinite loops are fine — as long as every path eventually reaches a break.

চার ধরনের loop — পরিস্থিতি অনুযায়ী বাছুন। break-এ বের হন, continue-এ পরের iteration-এ যান। Nested loop-এ labeled break দিয়ে একবারেই সবকটি থেকে বের হন। Infinite loop লিখলে exit অবশ্যই রাখুন।

Next Module → Methods — signatures, overloading, and varargs.