Programming and Java Fundamentals

For Loops

ReadingPreview

আপনি একটি free preview lesson দেখছেন।

Lesson Overview

Program-এ অনেক সময় একই কাজ একাধিকবার করতে হয়।

উদাহরণ:

  • 1 থেকে 10 পর্যন্ত number print করা
  • একটি message পাঁচবার দেখানো
  • Student marks যোগ করা
  • Multiplication table তৈরি করা
  • নির্দিষ্ট range-এর even number বের করা
  • একটি String-এর প্রতিটি character পড়া

একই statement বারবার manually লেখার পরিবর্তে Java-তে loop ব্যবহার করা হয়।

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

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

  • Loop কী
  • Iteration কী
  • for loop syntax
  • Initialization
  • Condition
  • Update expression
  • Loop counter
  • Forward এবং backward counting
  • Custom step size
  • Accumulator
  • Even এবং odd number
  • Multiplication table
  • Nested loop
  • String traversal
  • Infinite loop
  • Off-by-one error
  • Common for loop mistakes

Learning Objectives

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

  • Loop এবং iteration ব্যাখ্যা করতে
  • Basic for loop লিখতে
  • Initialization, condition এবং update expression বুঝতে
  • Forward এবং backward counting করতে
  • Custom increment বা decrement ব্যবহার করতে
  • Loop দিয়ে sum এবং product calculate করতে
  • Even এবং odd number process করতে
  • Multiplication table তৈরি করতে
  • Nested loop ব্যবহার করতে
  • String-এর character iterate করতে
  • Infinite loop এবং off-by-one error শনাক্ত করতে
  • Common loop-related bug fix করতে

What Is a Loop?

Loop হলো এমন একটি control-flow structure, যা একটি code block একাধিকবার execute করে।

Without loop:

System.out.println("Java");
System.out.println("Java");
System.out.println("Java");
System.out.println("Java");
System.out.println("Java");

With loop:

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

Output:

Java
Java
Java
Java
Java

What Is Iteration?

Loop block-এর প্রতিটি execution-কে একটি iteration বলা হয়।

for (int count = 1; count <= 3; count++) {
    System.out.println(count);
}

এখানে total তিনটি iteration হবে।

Iteration 1 → count = 1
Iteration 2 → count = 2
Iteration 3 → count = 3

Output:

1
2
3

Why Use Loops?

Loop ব্যবহার করলে:

  • Repeated code কমে
  • Code shorter হয়
  • Logic সহজে পরিবর্তন করা যায়
  • Dynamic number of repetitions handle করা যায়
  • Collection বা text traverse করা যায়
  • Calculation automate করা যায়
  • Manual mistakes কমে

Without loop:

System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);

With loop:

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

Basic for Loop Syntax

for (initialization; condition; update) {
    // Repeated statements
}

Example:

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

A for loop-এর তিনটি main অংশ:

  1. Initialization
  2. Condition
  3. Update expression

Understanding the Three Parts

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

Initialization

int number = 1

Loop শুরু হওয়ার আগে একবার execute হয়।

এখানে counter-এর initial value 1

Condition

number <= 5

প্রতিটি iteration-এর আগে check হয়।

Condition true হলে loop body execute হয়।

Condition false হলে loop শেষ হয়।

Update

number++

প্রতিটি iteration-এর পরে execute হয়।

এখানে number এক করে বাড়ে।


Execution Flow

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

Step-by-step:

Initialize number = 1
Check 1 <= 3 → true
Print 1
Increase number to 2

Check 2 <= 3 → true
Print 2
Increase number to 3

Check 3 <= 3 → true
Print 3
Increase number to 4

Check 4 <= 3 → false
Stop

Output:

1
2
3

The Loop Counter

Loop control করার জন্য ব্যবহৃত variable-কে loop counter বলা হয়।

Example:

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

এখানে:

count

loop counter।

Common short counter names:

i
j
k

Example:

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

Small এবং clear loop-এ i conventional।

Meaning গুরুত্বপূর্ণ হলে descriptive name ব্যবহার করুন:

for (
        int lessonNumber = 1;
        lessonNumber <= 10;
        lessonNumber++
) {
    System.out.println(
            "Lesson " + lessonNumber
    );
}

Counting Forward

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

Output:

1
2
3
4
5

Counting from Zero

Programming-এ অনেক sequence index 0 থেকে শুরু হয়।

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

Output:

0
1
2
3
4

এই loop পাঁচবার execute হয়।


< vs <=

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

Output:

1
2
3
4

কিন্তু:

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

Output:

1
2
3
4
5

Difference:

  • < 5 means 5 excluded
  • <= 5 means 5 included

Counting Backward

Decrement operator ব্যবহার করে reverse counting করা যায়।

for (int number = 5; number >= 1; number--) {
    System.out.println(number);
}

Output:

5
4
3
2
1

Countdown Example

for (int second = 5; second >= 1; second--) {
    System.out.println(second);
}

System.out.println("Start");

Output:

5
4
3
2
1
Start

Custom Step Size

Counter প্রতি iteration-এ শুধু 1 পরিবর্তন করতে হবে এমন নয়।


Increase by Two

for (int number = 0; number <= 10; number += 2) {
    System.out.println(number);
}

Output:

0
2
4
6
8
10

Increase by Five

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

Output:

5
10
15
20
25

Decrease by Two

for (int number = 10; number >= 0; number -= 2) {
    System.out.println(number);
}

Output:

10
8
6
4
2
0

Printing a Message Multiple Times

for (int count = 1; count <= 3; count++) {
    System.out.println(
            "Welcome to Java"
    );
}

Output:

Welcome to Java
Welcome to Java
Welcome to Java

Showing the Iteration Number

for (int count = 1; count <= 3; count++) {
    System.out.println(
            "Iteration: " + count
    );
}

Output:

Iteration: 1
Iteration: 2
Iteration: 3

Loop Variable Scope

Loop header-এর মধ্যে declare করা variable loop-এর বাইরে accessible নয়।

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

Invalid:

System.out.println(number);

number-এর scope for loop-এর মধ্যে সীমাবদ্ধ।


Declaring the Counter Outside

int number;

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

System.out.println(
        "Final value: " + number
);

Output:

1
2
3
4
5
Final value: 6

Loop শেষ হওয়ার সময় condition false হওয়ার জন্য number হয়েছে 6

সাধারণত counter শুধু loop-এর জন্য প্রয়োজন হলে loop header-এর মধ্যেই declare করা ভালো।


Accumulator

Loop চলাকালে result collect বা accumulate করার variable-কে accumulator বলা হয়।

Example:

int total = 0;

for (int number = 1; number <= 5; number++) {
    total += number;
}

System.out.println(total);

Output:

15

Calculation:

0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
10 + 5 = 15

Sum from 1 to N

int maximumNumber = 100;
int total = 0;

for (
        int number = 1;
        number <= maximumNumber;
        number++
) {
    total += number;
}

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

Output:

Total: 5050

Why Accumulator Starts at Zero

Addition-এর identity value হলো 0

0 + number = number

তাই sum accumulator সাধারণত:

int total = 0;

দিয়ে শুরু হয়।


Product Accumulator

একাধিক number multiply করতে accumulator 1 দিয়ে শুরু করতে হয়।

int product = 1;

for (int number = 1; number <= 5; number++) {
    product *= number;
}

System.out.println(product);

Output:

120

Calculation:

1 × 1 × 2 × 3 × 4 × 5 = 120

Why Product Should Not Start at Zero

Wrong:

int product = 0;

for (int number = 1; number <= 5; number++) {
    product *= number;
}

Result সবসময়:

0

কারণ:

0 × any number = 0

Correct:

int product = 1;

Factorial

একটি positive integer n-এর factorial:

n! = 1 × 2 × 3 × ... × n

Example:

5! = 120

Java program:

int number = 5;
long factorial = 1L;

for (int current = 1; current <= number; current++) {
    factorial *= current;
}

System.out.println(
        number + "! = " + factorial
);

Output:

5! = 120

long ব্যবহার করা হয়েছে কারণ factorial দ্রুত বড় হয়।


Sum of Even Numbers

int total = 0;

for (int number = 2; number <= 10; number += 2) {
    total += number;
}

System.out.println(total);

Output:

30

Calculation:

2 + 4 + 6 + 8 + 10 = 30

Even Numbers Using a Condition

for (int number = 1; number <= 10; number++) {
    if (number % 2 == 0) {
        System.out.println(number);
    }
}

Output:

2
4
6
8
10

Odd Numbers

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

Output:

1
3
5
7
9

Alternative:

for (int number = 1; number <= 10; number++) {
    if (number % 2 != 0) {
        System.out.println(number);
    }
}

Counting Matching Values

int evenNumberCount = 0;

for (int number = 1; number <= 10; number++) {
    if (number % 2 == 0) {
        evenNumberCount++;
    }
}

System.out.println(
        "Even numbers: "
        + evenNumberCount
);

Output:

Even numbers: 5

Multiplication Table

int number = 5;

for (int multiplier = 1; multiplier <= 10; multiplier++) {
    int result =
            number * multiplier;

    System.out.println(
            number
            + " × "
            + multiplier
            + " = "
            + result
    );
}

Output:

5 × 1 = 5
5 × 2 = 10
5 × 3 = 15
5 × 4 = 20
5 × 5 = 25
5 × 6 = 30
5 × 7 = 35
5 × 8 = 40
5 × 9 = 45
5 × 10 = 50

Calculating an Average

int total = 0;
int numberCount = 5;

for (int number = 1; number <= numberCount; number++) {
    total += number;
}

double average =
        total / (double) numberCount;

System.out.println(
        "Average: " + average
);

Output:

Average: 3.0

Reading Repeated User Input

import java.util.Scanner;

public class Main {

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

        int total = 0;
        int subjectCount = 3;

        for (
                int subjectNumber = 1;
                subjectNumber <= subjectCount;
                subjectNumber++
        ) {
            System.out.print(
                    "Enter mark for subject "
                    + subjectNumber
                    + ": "
            );

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

            total += mark;
        }

        double average =
                total / (double) subjectCount;

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

        System.out.println(
                "Average: " + average
        );

        scanner.close();
    }
}

Possible interaction:

Enter mark for subject 1: 80
Enter mark for subject 2: 90
Enter mark for subject 3: 85
Total: 255
Average: 85.0

Validating Repeated Input

for (int subject = 1; subject <= 3; subject++) {
    System.out.print(
            "Enter mark for subject "
            + subject
            + ": "
    );

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

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

এখানে invalid mark আবার input নেওয়া হচ্ছে না। Repeating validation while loop lesson-এ আরও ভালোভাবে শেখানো হবে।


Iterating Through a String

String-এর প্রতিটি character index দিয়ে access করা যায়।

String language = "Java";

for (
        int index = 0;
        index < language.length();
        index++
) {
    char character =
            language.charAt(index);

    System.out.println(character);
}

Output:

J
a
v
a

Why String Loop Uses < length()

String:

Java

Length:

4

Valid indexes:

0
1
2
3

তাই condition:

index < language.length()

Correct।

Wrong:

index <= language.length()

শেষ iteration-এ index 4 হবে এবং charAt(4) error দেবে।


Printing Characters with Index

String word = "Loop";

for (
        int index = 0;
        index < word.length();
        index++
) {
    System.out.println(
            index
            + ": "
            + word.charAt(index)
    );
}

Output:

0: L
1: o
2: o
3: p

Counting Characters

String value = "Java Foundation";
int letterACount = 0;

for (
        int index = 0;
        index < value.length();
        index++
) {
    char character =
            value.charAt(index);

    if (
            character == 'a'
            || character == 'A'
    ) {
        letterACount++;
    }
}

System.out.println(
        "A count: " + letterACount
);

Output:

A count: 3

Counting Vowels

String word = "education";
int vowelCount = 0;

for (
        int index = 0;
        index < word.length();
        index++
) {
    char character =
            Character.toLowerCase(
                    word.charAt(index)
            );

    if (
            character == 'a'
            || character == 'e'
            || character == 'i'
            || character == 'o'
            || character == 'u'
    ) {
        vowelCount++;
    }
}

System.out.println(
        "Vowels: " + vowelCount
);

Output:

Vowels: 5

Reversing a String

String word = "Java";
String reversed = "";

for (
        int index = word.length() - 1;
        index >= 0;
        index--
) {
    reversed += word.charAt(index);
}

System.out.println(reversed);

Output:

avaJ

Small example-এর জন্য এটি acceptable। বড় String-এর repeated concatenation-এর জন্য StringBuilder বেশি efficient।


Nested for Loops

একটি for loop-এর মধ্যে আরেকটি for loop থাকলে সেটি nested loop।

for (int row = 1; row <= 3; row++) {
    for (int column = 1; column <= 2; column++) {
        System.out.println(
                "Row "
                + row
                + ", Column "
                + column
        );
    }
}

Output:

Row 1, Column 1
Row 1, Column 2
Row 2, Column 1
Row 2, Column 2
Row 3, Column 1
Row 3, Column 2

How Nested Loops Work

Outer loop একবার execute হলে inner loop তার complete cycle চালায়।

Outer row = 1
    Inner column = 1
    Inner column = 2

Outer row = 2
    Inner column = 1
    Inner column = 2

Total iterations:

outer iterations × inner iterations

Example:

3 × 2 = 6

Printing a Rectangle Pattern

for (int row = 1; row <= 3; row++) {
    for (int column = 1; column <= 5; column++) {
        System.out.print("*");
    }

    System.out.println();
}

Output:

*****
*****
*****

Printing a Triangle Pattern

for (int row = 1; row <= 5; row++) {
    for (int column = 1; column <= row; column++) {
        System.out.print("*");
    }

    System.out.println();
}

Output:

*
**
***
****
*****

Multiplication Table Grid

for (int number = 1; number <= 3; number++) {
    System.out.println(
            "Table of " + number
    );

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

    System.out.println();
}

Multiple Variables in a for Loop

একটি for header-এ একই type-এর multiple variable ব্যবহার করা যায়।

for (
        int left = 1, right = 5;
        left <= 5;
        left++, right--
) {
    System.out.println(
            left + " - " + right
    );
}

Output:

1 - 5
2 - 4
3 - 3
4 - 2
5 - 1

এই syntax valid, তবে logic complex হলে readability কমতে পারে।


Omitting Initialization

Counter আগে declare করা থাকলে initialization part empty রাখা যায়।

int number = 1;

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

Omitting the Update

Update loop body-এর মধ্যে করা যায়।

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

    number++;
}

এটি valid, কিন্তু সাধারণ counting loop-এর জন্য update header-এ রাখা বেশি clear।


Infinite for Loop

সব তিনটি অংশ omit করলে infinite loop তৈরি হয়।

for (;;) {
    System.out.println("Running");
}

Condition না থাকায় loop automatically শেষ হবে না।

এই ধরনের loop থেকে বের হতে সাধারণত break, return বা exception প্রয়োজন।

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


Accidental Infinite Loop

Wrong:

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

Counter 1 থেকে কমছে:

1
0
-1
-2
...

Condition:

number <= 5

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

Correct:

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

Another Infinite Loop Mistake

Wrong:

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

Counter বাড়ছে, কিন্তু condition lower boundary check করছে।

Correct:

for (int number = 5; number >= 1; number--) {
    System.out.println(number);
}

Off-by-One Error

Loop expected সংখ্যার চেয়ে একবার বেশি বা কম execute হলে তাকে off-by-one error বলা হয়।

Expected:

1 to 5

Wrong:

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

Output:

1
2
3
4

Correct:

number <= 5

Index-Based Off-by-One Error

Wrong:

String word = "Java";

for (
        int index = 0;
        index <= word.length();
        index++
) {
    System.out.println(
            word.charAt(index)
    );
}

যখন index 4, charAt(4) invalid।

Correct:

index < word.length()

Empty Loop Body

Accidental semicolon:

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

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

Block loop শেষ হওয়ার পরে একবার execute হবে।

Correct:

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

Modifying the Counter Inside the Body

Confusing:

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

    number++;
}

Counter দুইবার বাড়ছে:

  • Loop body-এর মধ্যে
  • Update expression-এ

Output:

1
3
5
7
9

Custom step প্রয়োজন হলে header-এ লিখুন:

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

Changing the Loop Limit Inside the Loop

int limit = 5;

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

    limit++;
}

limit এবং number দুটোই বাড়ছে। Loop শেষ নাও হতে পারে।

Loop control variables unnecessarily modify করা avoid করুন।


Counter Overflow

Extreme loop-এ integer counter overflow হতে পারে।

for (
        int number = Integer.MAX_VALUE - 2;
        number <= Integer.MAX_VALUE;
        number++
) {
    System.out.println(number);
}

Integer.MAX_VALUE-এর পরে counter Integer.MIN_VALUE-এ wrap করতে পারে এবং condition unexpectedভাবে true থাকতে পারে।

Normal beginner loops-এ এটি uncommon, কিন্তু numeric range সম্পর্কে সচেতন থাকা প্রয়োজন।


Performance of Nested Loops

for (int row = 0; row < 1000; row++) {
    for (int column = 0; column < 1000; column++) {
        // Work
    }
}

Total inner executions:

1000 × 1000 = 1,000,000

Nested loop দ্রুত বড় workload তৈরি করতে পারে।

Loop লেখার সময় total iteration count বিবেচনা করুন।


Practical Example: Student Marks

import java.util.Scanner;

public class Main {

    static final int SUBJECT_COUNT = 3;
    static final int PASSING_MARK = 40;

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

        int totalMarks = 0;
        boolean passedAllSubjects = true;

        for (
                int subjectNumber = 1;
                subjectNumber <= SUBJECT_COUNT;
                subjectNumber++
        ) {
            System.out.print(
                    "Enter mark for subject "
                    + subjectNumber
                    + ": "
            );

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

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

                scanner.close();
                return;
            }

            totalMarks += mark;

            if (mark < PASSING_MARK) {
                passedAllSubjects = false;
            }
        }

        double averageMark =
                totalMarks
                / (double) SUBJECT_COUNT;

        String result =
                passedAllSubjects
                        ? "Passed"
                        : "Failed";

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

        System.out.println(
                "Average: "
                + "%.2f".formatted(
                        averageMark
                )
        );

        System.out.println(
                "Result: " + result
        );

        scanner.close();
    }
}

Practical Example: Range Statistics

int evenCount = 0;
int oddCount = 0;
int total = 0;

for (int number = 1; number <= 100; number++) {
    total += number;

    if (number % 2 == 0) {
        evenCount++;
    } else {
        oddCount++;
    }
}

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

System.out.println(
        "Even count: " + evenCount
);

System.out.println(
        "Odd count: " + oddCount
);

Output:

Total: 5050
Even count: 50
Odd count: 50

Practical Example: Search for a Character

String text = "Java Foundation";
char target = 'F';
int foundIndex = -1;

for (
        int index = 0;
        index < text.length();
        index++
) {
    if (text.charAt(index) == target) {
        foundIndex = index;
    }
}

System.out.println(
        "Found index: " + foundIndex
);

Output:

Found index: 5

এখানে loop match পাওয়ার পরও continue করছে। Early exit break lesson-এ শেখানো হবে।


Practical Example: Counting Digits

String value = "Course 2026 has 21 lessons";
int digitCount = 0;

for (
        int index = 0;
        index < value.length();
        index++
) {
    char character =
            value.charAt(index);

    if (Character.isDigit(character)) {
        digitCount++;
    }
}

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

Output:

Digit count: 6

Digits:

2 0 2 6 2 1

When to Use a for Loop

for loop ভালো choice যখন:

  • Repetition count জানা
  • Start এবং end value জানা
  • Counter প্রয়োজন
  • Range iterate করতে হবে
  • Index-based traversal করতে হবে
  • Fixed number of user inputs নিতে হবে
  • Nested grid বা pattern তৈরি করতে হবে

Examples:

Print 1–100
Read 5 marks
Traverse String indexes
Generate 10 table rows

When Another Loop May Be Better

যখন repetition count জানা নেই এবং condition true থাকা পর্যন্ত loop চলবে, তখন while loop বেশি natural হতে পারে।

Example:

Input valid না হওয়া পর্যন্ত আবার জিজ্ঞাসা করা
User exit না করা পর্যন্ত menu দেখানো
File-এর data শেষ না হওয়া পর্যন্ত পড়া

while এবং do-while পরবর্তী lesson-এ শেখানো হবে।


Common Mistakes

Wrong Update Direction

for (int number = 1; number <= 5; number--) {
}

Correct:

number++

Wrong Boundary

for (int number = 1; number < 5; number++) {
}

এটি 5 include করে না।


Semicolon After for

Wrong:

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

String Index Uses <=

Wrong:

index <= text.length()

Correct:

index < text.length()

Product Starts at Zero

Wrong:

int product = 0;

Correct:

int product = 1;

Counter Updated Twice

Avoid:

for (int number = 1; number <= 10; number++) {
    number++;
}

Unnecessary Nested Loop

Nested loop ব্যবহার করার আগে নিশ্চিত করুন inner repetition প্রয়োজন।

Unnecessary nesting performance এবং readability কমায়।


Testing a Loop

Loop test করার সময় check করুন:

  1. Initial value
  2. First iteration
  3. Last expected iteration
  4. Condition false হওয়ার value
  5. Update direction
  6. Total iteration count
  7. Empty range
  8. Boundary values
  9. Counter scope
  10. Accumulator initial value

Loop Trace Table

Code:

int total = 0;

for (int number = 1; number <= 3; number++) {
    total += number;
}

Trace:

Iterationnumbertotal beforetotal after
1101
2213
3336

Final:

total = 6

Trace table loop debugging-এর জন্য useful।


Practice Exercises

Exercise 1: Print 1 to 10

for loop ব্যবহার করে 1 থেকে 10 পর্যন্ত print করুন।


Exercise 2: Print 10 to 1

Reverse counting করুন।


Exercise 3: Print Even Numbers

1 থেকে 20 পর্যন্ত even numbers print করুন।


Exercise 4: Print Odd Numbers

1 থেকে 20 পর্যন্ত odd numbers print করুন।


Exercise 5: Sum from 1 to 100

Expected result:

5050

Exercise 6: Sum of Even Numbers

1 থেকে 100 পর্যন্ত even number-এর total calculate করুন।


Exercise 7: Multiplication Table

User-এর দেওয়া number-এর 1 থেকে 10 পর্যন্ত table print করুন।


Exercise 8: Factorial

User-এর দেওয়া non-negative integer-এর factorial calculate করুন।

Input:

5

Output:

120

Exercise 9: Read Five Marks

User-এর কাছ থেকে পাঁচটি mark নিন।

Calculate করুন:

  • Total
  • Average
  • কতটি subject passed
  • কতটি subject failed

Passing mark:

40

Exercise 10: Count Divisible Numbers

1 থেকে 100-এর মধ্যে কতটি number 3 দিয়ে divisible, count করুন।


Exercise 11: String Characters

একটি String-এর প্রতিটি character নতুন line-এ print করুন।


Exercise 12: Reverse a String

Loop ব্যবহার করে একটি String reverse করুন।


Exercise 13: Count Vowels

একটি English word বা sentence-এর vowel count বের করুন।


Exercise 14: Count Digits

Input:

Java 21 in 2026

কতটি digit আছে, count করুন।

Expected:

6

Exercise 15: Rectangle Pattern

Expected output:

****
****
****

Nested loop ব্যবহার করুন।


Exercise 16: Triangle Pattern

Expected output:

*
**
***
****
*****

Exercise 17: Multiplication Grid

1 থেকে 5 পর্যন্ত প্রতিটি number-এর 1 থেকে 10 table print করুন।


Exercise 18: Fix the Infinite Loop

for (int number = 1; number <= 10; number--) {
    System.out.println(number);
}

Exercise 19: Fix the Index Error

String text = "Java";

for (
        int index = 0;
        index <= text.length();
        index++
) {
    System.out.println(
            text.charAt(index)
    );
}

Exercise 20: Trace the Loop

int total = 0;

for (int number = 2; number <= 8; number += 2) {
    total += number;
}

প্রতিটি iteration-এর number এবং total লিখুন।


Knowledge Check

Question 1

Loop কী?

Question 2

Iteration কী?

Question 3

for loop-এর তিনটি main অংশ কী?

Question 4

Initialization কতবার execute হয়?

Question 5

Condition কখন check হয়?

Question 6

Update expression কখন execute হয়?

Question 7

number++ কী করে?

Question 8

number += 2 কী করে?

Question 9

< এবং <=-এর loop boundary difference কী?

Question 10

Backward loop-এর জন্য সাধারণত কোন update ব্যবহার করা হয়?

Question 11

Accumulator কী?

Question 12

Sum accumulator সাধারণত কোন value দিয়ে শুরু হয়?

Question 13

Product accumulator সাধারণত কোন value দিয়ে শুরু হয়?

Question 14

String-এর valid last index কী?

Question 15

String iterate করার condition সাধারণত কী?

Question 16

Nested loop কী?

Question 17

তিনবার outer এবং পাঁচবার inner loop চললে total inner execution কত?

Question 18

Infinite loop কী?

Question 19

Off-by-one error কী?

Question 20

for (;;) কী তৈরি করে?


Knowledge Check Answers

Answer 1

একটি code block একাধিকবার execute করা control-flow structure হলো loop।

Answer 2

Loop body-এর প্রতিটি execution একটি iteration।

Answer 3

  • Initialization
  • Condition
  • Update expression

Answer 4

Loop শুরু হওয়ার আগে একবার।

Answer 5

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

Answer 6

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

Answer 7

Variable-এর value 1 বাড়ায়।

Answer 8

Variable-এর value 2 বাড়ায়।

Answer 9

  • < limit limit exclude করে
  • <= limit limit include করে

Answer 10

number--

অথবা অন্য negative step।

Answer 11

Loop চলাকালে result collect বা update করা variable।

Answer 12

0

Answer 13

1

Answer 14

text.length() - 1

Answer 15

index < text.length()

Answer 16

একটি loop-এর মধ্যে আরেকটি loop।

Answer 17

3 × 5 = 15

Answer 18

যে loop condition কখনো false হয় না বা যার natural end নেই।

Answer 19

Loop expected সংখ্যার চেয়ে একবার বেশি বা কম execute হওয়ার error।

Answer 20

একটি infinite loop।


Lesson Summary

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

  • Loop repeated code execute করে
  • প্রতিটি loop execution একটি iteration
  • for loop initialization, condition এবং update নিয়ে গঠিত
  • Initialization একবার execute হয়
  • Condition প্রতিটি iteration-এর আগে check হয়
  • Update প্রতিটি iteration-এর পরে execute হয়
  • Counter forward বা backward যেতে পারে
  • Custom step size ব্যবহার করা যায়
  • < এবং <= boundary result পরিবর্তন করে
  • Accumulator sum, product এবং count collect করে
  • Sum সাধারণত 0 থেকে শুরু হয়
  • Product সাধারণত 1 থেকে শুরু হয়
  • Loop দিয়ে even, odd, factorial এবং multiplication table calculate করা যায়
  • String index দিয়ে character iterate করা যায়
  • String loop-এ index < length() ব্যবহার করতে হয়
  • Nested loop grid এবং pattern তৈরি করে
  • Infinite loop wrong condition বা update direction থেকে হতে পারে
  • Off-by-one error boundary ভুল হলে ঘটে
  • Loop counter unnecessarily body-এর মধ্যে modify করা উচিত নয়
  • Nested loop-এর total execution দ্রুত বড় হতে পারে
  • Trace table loop debugging সহজ করে
  • Repetition count জানা থাকলে for loop ভালো choice

Next Lesson

পরবর্তী lesson-এ আমরা while এবং do-while loops শিখব।

আমরা জানব:

  • Condition-controlled repetition
  • Basic while loop
  • do-while
  • while এবং for comparison
  • Input validation loop
  • Sentinel value
  • Menu loop
  • Infinite loop
  • At-least-once execution
  • Common loop mistakes