Programming and Java Fundamentals

While and Do-While Loops

ReadingPreview

You are viewing a free preview lesson.

Lesson Overview

for loop সাধারণত তখন ব্যবহার করা হয়, যখন repetition-এর সংখ্যা আগে থেকেই জানা থাকে।

কিন্তু অনেক situation-এ আমরা জানি না loop ঠিক কতবার চলবে।

উদাহরণ:

  • User valid input না দেওয়া পর্যন্ত আবার input নেওয়া
  • Correct password না দেওয়া পর্যন্ত চেষ্টা করা
  • Account balance শেষ না হওয়া পর্যন্ত transaction চালানো
  • User exit option select না করা পর্যন্ত menu দেখানো
  • কোনো value একটি নির্দিষ্ট condition satisfy করা পর্যন্ত process চালানো

এই ধরনের condition-controlled repetition-এর জন্য Java-তে while এবং do-while loop ব্যবহার করা হয়।

এই lesson-এ আমরা শিখব:

  • while loop
  • do-while loop
  • Entry-controlled এবং exit-controlled loop
  • Counter-controlled while
  • Input validation loop
  • Sentinel value
  • Menu loop
  • Accumulator
  • for, while এবং do-while comparison
  • Infinite loop
  • Common loop mistakes

Learning Objectives

এই lesson শেষ করার পর আপনি পারবেন:

  • while loop-এর execution flow ব্যাখ্যা করতে
  • Condition true থাকা পর্যন্ত loop চালাতে
  • Counter-controlled while loop লিখতে
  • do-while loop ব্যবহার করতে
  • At-least-once execution বুঝতে
  • User input validate করতে
  • Sentinel value ব্যবহার করতে
  • Menu-driven console program লিখতে
  • for, while এবং do-while-এর মধ্যে উপযুক্ত loop নির্বাচন করতে
  • Infinite loop এবং update-related bug শনাক্ত করতে

What Is a While Loop?

while হলো একটি condition-controlled loop।

Condition true থাকা পর্যন্ত loop body execute হয়।

Syntax:

while (condition) {
    // Repeated statements
}

Example:

int number = 1;

while (number <= 5) {
    System.out.println(number);

    number++;
}

Output:

1
2
3
4
5

How a While Loop Works

while (condition) {
    // Body
}

Execution:

  1. Condition check হয়
  2. Condition true হলে body execute হয়
  3. Body শেষ হলে আবার condition check হয়
  4. Condition false হলে loop শেষ হয়

While Loop Execution Flow

int number = 1;

while (number <= 3) {
    System.out.println(number);

    number++;
}

Step-by-step:

number = 1
1 <= 3 → true
Print 1
number becomes 2

2 <= 3 → true
Print 2
number becomes 3

3 <= 3 → true
Print 3
number becomes 4

4 <= 3 → false
Stop

While Is Entry-Controlled

while loop body execute হওয়ার আগে condition check করে।

এই কারণে condition শুরুতেই false হলে body একবারও execute হবে না।

int number = 10;

while (number < 5) {
    System.out.println(number);
}

Output:

No output

Condition:

10 < 5 → false

Counter-Controlled While Loop

while loop-এ counter manually manage করতে হয়।

int count = 1;

while (count <= 5) {
    System.out.println(
            "Iteration: " + count
    );

    count++;
}

Output:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

The Three Parts of a Counter Loop

int count = 1;

while (count <= 5) {
    System.out.println(count);

    count++;
}

Parts:

Initialization

int count = 1;

Condition

count <= 5

Update

count++;

for loop-এ এই তিনটি header-এর মধ্যে থাকে। while loop-এ আলাদাভাবে লেখা হয়।


Counting Backward

int number = 5;

while (number >= 1) {
    System.out.println(number);

    number--;
}

Output:

5
4
3
2
1

Custom Step Size

int number = 0;

while (number <= 10) {
    System.out.println(number);

    number += 2;
}

Output:

0
2
4
6
8
10

Accumulator with While

int number = 1;
int total = 0;

while (number <= 5) {
    total += number;

    number++;
}

System.out.println(total);

Output:

15

Product with While

int number = 1;
int product = 1;

while (number <= 5) {
    product *= number;

    number++;
}

System.out.println(product);

Output:

120

When to Use While

while loop ভালো choice যখন:

  • Repetition count আগে জানা নেই
  • একটি condition true থাকা পর্যন্ত loop চলবে
  • User input-এর ওপর loop depend করে
  • Sentinel value পাওয়া পর্যন্ত data পড়তে হবে
  • User exit না করা পর্যন্ত menu চলবে
  • External state পরিবর্তন হওয়া পর্যন্ত process চলবে

Input Validation with While

User valid age না দেওয়া পর্যন্ত input নিতে চাই।

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter your age: "
        );

        int age =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        while (age < 0 || age > 150) {
            System.out.println(
                    "Invalid age"
            );

            System.out.print(
                    "Enter an age between 0 and 150: "
            );

            age =
                    Integer.parseInt(
                            scanner
                                    .nextLine()
                                    .strip()
                    );
        }

        System.out.println(
                "Valid age: " + age
        );

        scanner.close();
    }
}

Why the Input Must Be Updated

Wrong:

int age = -10;

while (age < 0 || age > 150) {
    System.out.println("Invalid age");
}

age কখনো change হচ্ছে না।

Condition সবসময় true থাকবে।

Result:

Infinite loop

Correct:

while (age < 0 || age > 150) {
    age = readNewAge();
}

Loop condition-এর value body-এর মধ্যে পরিবর্তনের সুযোগ থাকতে হবে।


Reading Valid Marks

System.out.print(
        "Enter a mark between 0 and 100: "
);

int mark =
        Integer.parseInt(
                scanner
                        .nextLine()
                        .strip()
        );

while (mark < 0 || mark > 100) {
    System.out.println(
            "Invalid mark"
    );

    System.out.print(
            "Enter a mark between 0 and 100: "
    );

    mark =
            Integer.parseInt(
                    scanner
                            .nextLine()
                            .strip()
            );
}

Loop শুধু valid mark পাওয়ার পর শেষ হবে।


Validating a Non-Blank String

System.out.print(
        "Enter your name: "
);

String name =
        scanner
                .nextLine()
                .strip();

while (name.isBlank()) {
    System.out.println(
            "Name is required"
    );

    System.out.print(
            "Enter your name: "
    );

    name =
            scanner
                    .nextLine()
                    .strip();
}

System.out.println(
        "Welcome, " + name
);

Reading Until a Condition Is Met

int number = 1;

while (number < 100) {
    number *= 2;

    System.out.println(number);
}

Output:

2
4
8
16
32
64
128

Loop stop হয়েছে যখন:

number < 100

false হয়েছে।


Sentinel Value

Sentinel হলো একটি special value, যা input sequence শেষ করার signal হিসেবে ব্যবহার করা হয়।

Example:

Enter numbers
Enter -1 to stop

এখানে:

-1

sentinel value।


Sentinel-Controlled Loop

import java.util.Scanner;

public class Main {

    static final int SENTINEL = -1;

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        int total = 0;

        System.out.print(
                "Enter a number or -1 to stop: "
        );

        int number =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        while (number != SENTINEL) {
            total += number;

            System.out.print(
                    "Enter a number or -1 to stop: "
            );

            number =
                    Integer.parseInt(
                            scanner
                                    .nextLine()
                                    .strip()
                    );
        }

        System.out.println(
                "Total: " + total
        );

        scanner.close();
    }
}

Possible interaction:

Enter a number or -1 to stop: 10
Enter a number or -1 to stop: 20
Enter a number or -1 to stop: 5
Enter a number or -1 to stop: -1
Total: 35

Sentinel total-এর মধ্যে যোগ করা হয়নি।


Counting Sentinel Input Values

int total = 0;
int count = 0;

while (number != SENTINEL) {
    total += number;
    count++;

    number =
            Integer.parseInt(
                    scanner
                            .nextLine()
                            .strip()
            );
}

Average:

if (count > 0) {
    double average =
            total / (double) count;
}

Zero values entered হলে division by zero avoid করতে count > 0 check প্রয়োজন।


What Is a Do-While Loop?

do-while loop body আগে execute করে, তারপর condition check করে।

Syntax:

do {
    // Statements
} while (condition);

শেষে semicolon required:

;

Basic Do-While Example

int number = 1;

do {
    System.out.println(number);

    number++;
} while (number <= 5);

Output:

1
2
3
4
5

Do-While Is Exit-Controlled

do-while condition body execute হওয়ার পরে check করে।

তাই body অন্তত একবার execute হয়।

int number = 10;

do {
    System.out.println(number);
} while (number < 5);

Output:

10

Condition শুরু থেকেই false, তবুও body একবার execute হয়েছে।


While vs Do-While

While

while (condition) {
    // Body
}
  • Condition আগে check হয়
  • Body zero বা more times execute হয়

Do-While

do {
    // Body
} while (condition);
  • Body আগে execute হয়
  • Condition পরে check হয়
  • Body at least once execute হয়

Same False Condition, Different Result

While

int value = 10;

while (value < 5) {
    System.out.println(value);
}

Output:

No output

Do-While

int value = 10;

do {
    System.out.println(value);
} while (value < 5);

Output:

10

Input Validation with Do-While

User-কে অন্তত একবার prompt দেখাতে হবে। এই case-এ do-while natural।

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        int mark;

        do {
            System.out.print(
                    "Enter a mark between 0 and 100: "
            );

            mark =
                    Integer.parseInt(
                            scanner
                                    .nextLine()
                                    .strip()
                    );

            if (mark < 0 || mark > 100) {
                System.out.println(
                        "Invalid mark"
                );
            }
        } while (mark < 0 || mark > 100);

        System.out.println(
                "Valid mark: " + mark
        );

        scanner.close();
    }
}

Why Do-While Fits Input Prompts

Input নেওয়ার আগে valid কি না জানা যায় না।

এই flow:

  1. Prompt দেখান
  2. Input নিন
  3. Validate করুন
  4. Invalid হলে repeat করুন

do-while-এর structure-এর সঙ্গে naturally match করে।


Menu with Do-While

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        int option;

        do {
            System.out.println();
            System.out.println("1. View courses");
            System.out.println("2. Create course");
            System.out.println("3. Exit");

            System.out.print(
                    "Choose an option: "
            );

            option =
                    Integer.parseInt(
                            scanner
                                    .nextLine()
                                    .strip()
                    );

            switch (option) {
                case 1 ->
                        System.out.println(
                                "Loading courses"
                        );

                case 2 ->
                        System.out.println(
                                "Opening course form"
                        );

                case 3 ->
                        System.out.println(
                                "Goodbye"
                        );

                default ->
                        System.out.println(
                                "Invalid option"
                        );
            }
        } while (option != 3);

        scanner.close();
    }
}

Menu অন্তত একবার display হবে।

User 3 select না করা পর্যন্ত repeat হবে।


Menu with While

একই menu while দিয়ে:

int option = 0;

while (option != 3) {
    System.out.println("1. View courses");
    System.out.println("2. Create course");
    System.out.println("3. Exit");

    option =
            Integer.parseInt(
                    scanner
                            .nextLine()
                            .strip()
            );

    switch (option) {
        case 1 ->
                System.out.println(
                        "Loading courses"
                );

        case 2 ->
                System.out.println(
                        "Opening course form"
                );

        case 3 ->
                System.out.println(
                        "Goodbye"
                );

        default ->
                System.out.println(
                        "Invalid option"
                );
    }
}

এখানে initial value:

int option = 0;

দিতে হয়েছে, যাতে condition প্রথমবার true হয়।

do-while menu-এর জন্য কখনো বেশি natural।


Password Attempt Example

import java.util.Scanner;

public class Main {

    static final String CORRECT_PASSWORD =
            "java123";

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        String password = "";

        while (
                !CORRECT_PASSWORD.equals(
                        password
                )
        ) {
            System.out.print(
                    "Enter password: "
            );

            password =
                    scanner.nextLine();

            if (
                    !CORRECT_PASSWORD.equals(
                            password
                    )
            ) {
                System.out.println(
                        "Incorrect password"
                );
            }
        }

        System.out.println(
                "Access granted"
        );

        scanner.close();
    }
}

Password with Limited Attempts

import java.util.Scanner;

public class Main {

    static final String CORRECT_PASSWORD =
            "java123";

    static final int MAXIMUM_ATTEMPTS = 3;

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        int attemptCount = 0;
        boolean authenticated = false;

        while (
                attemptCount < MAXIMUM_ATTEMPTS
                && !authenticated
        ) {
            System.out.print(
                    "Enter password: "
            );

            String password =
                    scanner.nextLine();

            attemptCount++;

            if (
                    CORRECT_PASSWORD.equals(
                            password
                    )
            ) {
                authenticated = true;
            } else {
                int remainingAttempts =
                        MAXIMUM_ATTEMPTS
                        - attemptCount;

                System.out.println(
                        "Incorrect password"
                );

                System.out.println(
                        "Remaining attempts: "
                        + remainingAttempts
                );
            }
        }

        if (authenticated) {
            System.out.println(
                    "Access granted"
            );
        } else {
            System.out.println(
                    "Account locked"
            );
        }

        scanner.close();
    }
}

Loop stop হবে যখন:

  • Maximum attempts complete
  • অথবা authentication successful

Multiple Conditions in While

while (
        attemptCount < MAXIMUM_ATTEMPTS
        && !authenticated
) {
}

Loop চলবে যখন দুই condition-ই true:

  • Attempts remaining
  • User authenticated নয়

Reading Until Blank Input

System.out.print(
        "Enter text or leave blank to stop: "
);

String input =
        scanner.nextLine();

while (!input.isBlank()) {
    System.out.println(
            "You entered: " + input
    );

    System.out.print(
            "Enter text or leave blank to stop: "
    );

    input =
            scanner.nextLine();
}

Blank line sentinel হিসেবে কাজ করছে।


Running Total Until Zero

int total = 0;

System.out.print(
        "Enter a number or 0 to stop: "
);

int number =
        Integer.parseInt(
                scanner
                        .nextLine()
                        .strip()
        );

while (number != 0) {
    total += number;

    System.out.print(
            "Enter a number or 0 to stop: "
    );

    number =
            Integer.parseInt(
                    scanner
                            .nextLine()
                            .strip()
            );
}

System.out.println(
        "Total: " + total
);

Guessing Game

import java.util.Scanner;

public class Main {

    static final int SECRET_NUMBER = 7;

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        int guess = 0;

        while (guess != SECRET_NUMBER) {
            System.out.print(
                    "Guess the number: "
            );

            guess =
                    Integer.parseInt(
                            scanner
                                    .nextLine()
                                    .strip()
                    );

            if (guess < SECRET_NUMBER) {
                System.out.println(
                        "Too low"
                );
            } else if (
                    guess > SECRET_NUMBER
            ) {
                System.out.println(
                        "Too high"
                );
            } else {
                System.out.println(
                        "Correct"
                );
            }
        }

        scanner.close();
    }
}

Calculating Digits of a Number

int number = 12345;
int digitCount = 0;

while (number != 0) {
    number /= 10;

    digitCount++;
}

System.out.println(
        "Digit count: " + digitCount
);

Output:

Digit count: 5

Handling Zero in Digit Count

Previous code-এ input 0 হলে loop একবারও চলবে না এবং count হবে 0

কিন্তু numeric 0-এর একটি digit আছে।

Correct:

int number = 0;
int digitCount;

if (number == 0) {
    digitCount = 1;
} else {
    digitCount = 0;

    while (number != 0) {
        number /= 10;

        digitCount++;
    }
}

Sum of Digits

int number = 12345;
int total = 0;

while (number != 0) {
    int digit = number % 10;

    total += digit;
    number /= 10;
}

System.out.println(
        "Digit total: " + total
);

Output:

Digit total: 15

Calculation:

1 + 2 + 3 + 4 + 5 = 15

Reverse a Number

int number = 1234;
int reversedNumber = 0;

while (number != 0) {
    int digit = number % 10;

    reversedNumber =
            reversedNumber * 10
            + digit;

    number /= 10;
}

System.out.println(
        reversedNumber
);

Output:

4321

Palindrome Number

একটি number reverse করার পর original-এর সমান হলে palindrome।

int originalNumber = 1221;
int remainingNumber = originalNumber;
int reversedNumber = 0;

while (remainingNumber != 0) {
    int digit =
            remainingNumber % 10;

    reversedNumber =
            reversedNumber * 10
            + digit;

    remainingNumber /= 10;
}

boolean palindrome =
        originalNumber
        == reversedNumber;

System.out.println(
        "Palindrome: " + palindrome
);

Output:

Palindrome: true

Converting a For Loop to While

For loop:

for (int number = 1; number <= 5; number++) {
    System.out.println(number);
}

Equivalent while:

int number = 1;

while (number <= 5) {
    System.out.println(number);

    number++;
}

Converting a While Loop to For

While:

int number = 1;

while (number <= 5) {
    System.out.println(number);

    number++;
}

For:

for (int number = 1; number <= 5; number++) {
    System.out.println(number);
}

Counter-based fixed repetition-এর জন্য for সাধারণত বেশি concise।


For vs While vs Do-While

LoopBest Use
forRepetition count বা range জানা
whileCondition true থাকা পর্যন্ত repetition
do-whileBody অন্তত একবার execute করতে হবে

Choosing the Right Loop

Use for

Print 1 to 100
Read exactly 5 marks
Traverse String indexes

Use while

Password correct না হওয়া পর্যন্ত চেষ্টা
Sentinel পাওয়া পর্যন্ত input
Balance positive থাকা পর্যন্ত transaction

Use do-while

Menu অন্তত একবার দেখানো
Input অন্তত একবার নেওয়া
User continue করবে কি না জিজ্ঞাসা করা

Infinite While Loop

while (true) {
    System.out.println("Running");
}

Condition সবসময় true।

এটি intentional infinite loop হতে পারে।

Loop থেকে বের হওয়ার জন্য break, return বা exception প্রয়োজন।

break পরবর্তী lesson-এ বিস্তারিত শেখানো হবে।


Accidental Infinite Loop

Wrong:

int number = 1;

while (number <= 5) {
    System.out.println(number);
}

number update হচ্ছে না।

Correct:

number++;

Wrong Update Direction

Wrong:

int number = 1;

while (number <= 5) {
    System.out.println(number);

    number--;
}

Counter কমছে:

1
0
-1
-2
...

Condition সবসময় true থাকে।

Correct:

number++;

Stale Condition Variable

boolean active = true;

while (active) {
    System.out.println("Running");
}

active কখনো false হচ্ছে না।

Loop indefinite চলবে।

Condition variable কোথায় এবং কীভাবে পরিবর্তিত হবে, তা clear হওয়া প্রয়োজন।


Assignment Inside a Condition

Risky:

boolean active = false;

while (active = true) {
    System.out.println("Running");
}

এখানে comparison নয়, true assignment হয়েছে।

Condition সবসময় true।

Correct:

while (active) {
}

অথবা comparison প্রয়োজন হলে:

while (active == true) {
}

প্রথম version বেশি idiomatic।


Semicolon After While

Wrong:

int number = 1;

while (number <= 5); {
    System.out.println(number);

    number++;
}

Semicolon empty loop body তৈরি করে।

number empty loop-এর মধ্যে change হচ্ছে না।

Result infinite loop।

Correct:

while (number <= 5) {
    System.out.println(number);

    number++;
}

Do-While Semicolon

do-while-এর শেষে semicolon required।

Correct:

do {
    number++;
} while (number <= 5);

Wrong:

do {
    number++;
} while (number <= 5)

Updating Too Early

int number = 1;

while (number <= 5) {
    number++;

    System.out.println(number);
}

Output:

2
3
4
5
6

যদি expected 1–5 হয়, print update-এর আগে করতে হবে।

while (number <= 5) {
    System.out.println(number);

    number++;
}

Repeating Prompt Without Reading New Input

Wrong:

String name = "";

while (name.isBlank()) {
    System.out.println(
            "Name is required"
    );
}

New input নেওয়া হচ্ছে না।

Correct:

while (name.isBlank()) {
    System.out.print(
            "Enter your name: "
    );

    name =
            scanner
                    .nextLine()
                    .strip();
}

Sentinel Collision

যদি -1 valid data হতে পারে, তাহলে -1 sentinel হিসেবে ব্যবহার করলে ambiguity তৈরি হবে।

Sentinel এমন value হওয়া উচিত যা normal valid input-এর অংশ নয়।

Example:

  • Marks 0–100 হলে -1 suitable sentinel
  • Temperature-এর জন্য -1 valid হতে পারে, তাই অন্য termination mechanism প্রয়োজন

Common Input Parsing Risk

int age =
        Integer.parseInt(
                scanner.nextLine()
        );

User non-numeric input দিলে NumberFormatException হবে।

Loop validation শুধু range error handle করতে পারে; format error-এর জন্য exception handling প্রয়োজন।

Exception handling future lesson-এ শেখানো হবে।


Practical Example: Validated Grade Input

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        int mark;

        do {
            System.out.print(
                    "Enter a mark between 0 and 100: "
            );

            mark =
                    Integer.parseInt(
                            scanner
                                    .nextLine()
                                    .strip()
                    );

            if (mark < 0 || mark > 100) {
                System.out.println(
                        "Invalid mark"
                );
            }
        } while (mark < 0 || mark > 100);

        String grade;

        if (mark >= 80) {
            grade = "A";
        } else if (mark >= 70) {
            grade = "B";
        } else if (mark >= 60) {
            grade = "C";
        } else if (mark >= 50) {
            grade = "D";
        } else if (mark >= 40) {
            grade = "E";
        } else {
            grade = "F";
        }

        System.out.println(
                "Grade: " + grade
        );

        scanner.close();
    }
}

Practical Example: Repeated Course Menu

import java.util.Scanner;

public class Main {

    static final int VIEW_COURSES = 1;
    static final int CREATE_COURSE = 2;
    static final int EXIT = 3;

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        int option;

        do {
            System.out.println();
            System.out.println(
                    VIEW_COURSES
                    + ". View courses"
            );

            System.out.println(
                    CREATE_COURSE
                    + ". Create course"
            );

            System.out.println(
                    EXIT + ". Exit"
            );

            System.out.print(
                    "Choose an option: "
            );

            option =
                    Integer.parseInt(
                            scanner
                                    .nextLine()
                                    .strip()
                    );

            switch (option) {
                case VIEW_COURSES ->
                        System.out.println(
                                "Courses loaded"
                        );

                case CREATE_COURSE ->
                        System.out.println(
                                "Course form opened"
                        );

                case EXIT ->
                        System.out.println(
                                "Application closed"
                        );

                default ->
                        System.out.println(
                                "Invalid option"
                        );
            }
        } while (option != EXIT);

        scanner.close();
    }
}

Practical Example: Number Statistics

User 0 দিলে input শেষ হবে।

import java.util.Scanner;

public class Main {

    static final int SENTINEL = 0;

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        int total = 0;
        int count = 0;
        int positiveCount = 0;
        int negativeCount = 0;

        System.out.print(
                "Enter a number or 0 to stop: "
        );

        int number =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        while (number != SENTINEL) {
            total += number;
            count++;

            if (number > 0) {
                positiveCount++;
            } else {
                negativeCount++;
            }

            System.out.print(
                    "Enter a number or 0 to stop: "
            );

            number =
                    Integer.parseInt(
                            scanner
                                    .nextLine()
                                    .strip()
                    );
        }

        System.out.println();
        System.out.println(
                "Values entered: " + count
        );

        System.out.println(
                "Positive values: "
                + positiveCount
        );

        System.out.println(
                "Negative values: "
                + negativeCount
        );

        System.out.println(
                "Total: " + total
        );

        if (count > 0) {
            double average =
                    total / (double) count;

            System.out.println(
                    "Average: "
                    + "%.2f".formatted(
                            average
                    )
            );
        } else {
            System.out.println(
                    "No values entered"
            );
        }

        scanner.close();
    }
}

Common Mistakes

Missing Update

while (count <= 5) {
    System.out.println(count);
}

Wrong Update Direction

while (count <= 5) {
    count--;
}

Extra Semicolon

while (count <= 5); {
}

Assignment Instead of Condition

while (active = true) {
}

Input Not Refreshed

while (mark < 0) {
    System.out.println("Invalid");
}

Wrong Sentinel Choice

Normal valid input-এর সঙ্গে sentinel conflict করা।

Division by Zero

No values entered হলেও average calculate করা।

Missing Do-While Semicolon

do {
} while (condition)

Testing While Loops

Test করুন:

  1. Condition শুরুতেই false
  2. Condition শুরুতেই true
  3. Exactly one iteration
  4. Multiple iterations
  5. Last valid value
  6. First invalid value
  7. Counter update হচ্ছে কি না
  8. Update direction correct কি না
  9. Sentinel প্রথম input হিসেবে দেওয়া
  10. কোনো value ছাড়া average calculation
  11. Empty এবং blank input
  12. Exit option প্রথমবার select করা

Loop Trace Example

int number = 1;
int total = 0;

while (number <= 3) {
    total += number;

    number++;
}
Iterationnumber beforetotal afternumber after
1112
2233
3364

Final:

number = 4
total = 6

Practice Exercises

Exercise 1: Count from 1 to 10

while loop ব্যবহার করে print করুন।


Exercise 2: Reverse Countdown

10 থেকে 1 পর্যন্ত print করুন।


Exercise 3: Even Numbers

2 থেকে 20 পর্যন্ত even numbers while দিয়ে print করুন।


Exercise 4: Sum from 1 to 100

Expected:

5050

Exercise 5: Factorial

while loop দিয়ে 5! calculate করুন।

Expected:

120

Exercise 6: Valid Age Input

User valid age 0–150 না দেওয়া পর্যন্ত আবার input নিন।


Exercise 7: Valid Mark with Do-While

0–100 range-এর valid mark না পাওয়া পর্যন্ত prompt repeat করুন।


Exercise 8: Non-Blank Name

User blank name দিলে আবার input নিন।


Exercise 9: Sentinel Total

User number input দেবে।

-1 দিলে input শেষ হবে।

সব input-এর total calculate করুন।


Exercise 10: Sentinel Average

User 0 না দেওয়া পর্যন্ত number নিন।

Calculate করুন:

  • Count
  • Total
  • Average

Exercise 11: Password Attempts

Correct password এবং maximum three attempts ব্যবহার করুন।

Result:

Access granted

অথবা:

Account locked

Exercise 12: Guessing Game

একটি secret number define করুন।

User correct number না বলা পর্যন্ত input নিন।

Hints দিন:

Too high
Too low
Correct

Exercise 13: Menu Loop

Menu:

1. Add
2. Subtract
3. Exit

User exit না করা পর্যন্ত menu repeat করুন।


Exercise 14: Count Digits

একটি positive integer-এর digit count বের করুন।


Exercise 15: Sum of Digits

Input:

12345

Expected:

15

Exercise 16: Reverse a Number

Input:

1234

Expected:

4321

Exercise 17: Palindrome Number

Input:

1221

Expected:

Palindrome: true

Exercise 18: Convert For to While

Rewrite করুন:

for (int number = 1; number <= 5; number++) {
    System.out.println(number);
}

Exercise 19: Convert While to For

Rewrite করুন:

int number = 10;

while (number >= 1) {
    System.out.println(number);

    number--;
}

Exercise 20: Fix the Infinite Loop

int number = 1;

while (number <= 5) {
    System.out.println(number);
}

Exercise 21: Fix the Direction

int number = 1;

while (number <= 10) {
    System.out.println(number);

    number--;
}

Exercise 22: Fix the Semicolon

while (count < 5); {
    count++;
}

Exercise 23: Choose the Loop

নিচের জন্য for, while নাকি do-while নির্বাচন করুন:

  1. Exactly 10 times print করা
  2. User exit না করা পর্যন্ত menu
  3. Valid input না পাওয়া পর্যন্ত prompt
  4. String-এর সব indexes traverse করা
  5. Password correct না হওয়া পর্যন্ত চেষ্টা
  6. পাঁচটি mark নেওয়া
  7. Sentinel পাওয়া পর্যন্ত number পড়া

Knowledge Check

Question 1

while loop কী?

Question 2

while condition কখন check হয়?

Question 3

Condition শুরুতেই false হলে while body কয়বার execute হয়?

Question 4

while loop-এ counter কোথায় initialize করা হয়?

Question 5

Counter update না করলে কী হতে পারে?

Question 6

Sentinel value কী?

Question 7

Sentinel total-এর মধ্যে process করা উচিত কি?

Question 8

do-while condition কখন check হয়?

Question 9

do-while body minimum কয়বার execute হয়?

Question 10

do-while-এর শেষে semicolon লাগে কি?

Question 11

Input validation-এর জন্য do-while useful কেন?

Question 12

for এবং while-এর main difference কী?

Question 13

Menu loop-এর জন্য do-while useful কেন?

Question 14

while (true) কী তৈরি করে?

Question 15

Assignment inside condition কী problem তৈরি করতে পারে?

Question 16

while (condition); কী problem তৈরি করে?

Question 17

Average calculate করার আগে count check করা কেন প্রয়োজন?

Question 18

Wrong update direction কী ঘটাতে পারে?

Question 19

Entry-controlled loop কোনটি?

Question 20

Exit-controlled loop কোনটি?


Knowledge Check Answers

Answer 1

Condition true থাকা পর্যন্ত একটি code block repeat করা loop হলো while

Answer 2

প্রতিটি iteration-এর আগে।

Answer 3

Zero times।

Answer 4

সাধারণত loop-এর আগে।

Answer 5

Infinite loop হতে পারে।

Answer 6

Input sequence শেষ করার signal হিসেবে ব্যবহৃত special value।

Answer 7

না, যদি sentinel শুধু termination signal হয়।

Answer 8

Loop body execute হওয়ার পরে।

Answer 9

At least one time।

Answer 10

হ্যাঁ।

} while (condition);

Answer 11

Input অন্তত একবার নিতে হয় এবং তারপর validity check করা হয়।

Answer 12

for fixed বা counter-based repetition-এর জন্য concise। while condition-controlled unknown repetition-এর জন্য natural।

Answer 13

Menu অন্তত একবার display করতে হয়।

Answer 14

একটি infinite loop।

Answer 15

Comparison-এর পরিবর্তে value assign হতে পারে এবং condition unexpectedly always true হতে পারে।

Answer 16

Semicolon empty loop body তৈরি করতে পারে।

Answer 17

Count 0 হলে division by zero হবে।

Answer 18

Loop expected condition থেকে দূরে যেতে পারে এবং infinite হতে পারে।

Answer 19

while

Answer 20

do-while


Lesson Summary

এই lesson-এ আমরা শিখেছি:

  • while condition-controlled repetition চালায়
  • while condition body-এর আগে check করে
  • Condition false হলে body একবারও execute নাও হতে পারে
  • Counter-controlled while-এ initialization, condition এবং update আলাদাভাবে লেখা হয়
  • Counter update না করলে infinite loop হতে পারে
  • Input validation-এর জন্য while useful
  • Sentinel value input sequence শেষ করতে পারে
  • Sentinel normal data-এর সঙ্গে conflict করা উচিত নয়
  • do-while body আগে execute করে
  • do-while body অন্তত একবার execute হয়
  • do-while-এর শেষে semicolon প্রয়োজন
  • Menu এবং at-least-once input flow-এর জন্য do-while natural
  • Multiple condition দিয়ে attempt limit এবং success state control করা যায়
  • while দিয়ে digit count, digit sum এবং number reverse করা যায়
  • Fixed repetition-এর জন্য for বেশি concise
  • Unknown condition-based repetition-এর জন্য while suitable
  • At-least-once repetition-এর জন্য do-while suitable
  • Extra semicolon, missing update এবং wrong update direction common loop bug
  • Average calculation-এর আগে input count check করা প্রয়োজন
  • Loop trace table execution বুঝতে সাহায্য করে

Next Lesson

পরবর্তী lesson-এ আমরা loop control statements শিখব।

আমরা জানব:

  • break
  • continue
  • Early loop termination
  • Skipping an iteration
  • Search loop
  • Input filtering
  • Nested loop control
  • Labeled break
  • Labeled continue
  • Common control-flow mistakes