Java for Loop

Introduction

The for loop is one of the most commonly used control flow statements in Java, allowing you to execute a block of code a specific number of times. It is particularly useful when you know in advance how many times you need to iterate. In this chapter, we will explore how the for loop works, its syntax, and various use cases with examples and detailed comments.

How the for Loop Works

The for loop in Java consists of three main parts:

  1. Initialization: Executed once at the beginning of the loop to initialize the loop control variable(s).
  2. Condition: Evaluated before each iteration. If true, the loop body is executed; if false, the loop terminates.
  3. Update: Executed after each iteration to update the loop control variable(s).

The general flow of the for loop can be visualized as follows:

Initialization
    |
    v
Condition -> True -> Execute Loop Body -> Update -> Condition
    |
    v
  False
    |
    v
  End Loop

Syntax

The basic syntax of the for loop is as follows:

for (initialization; condition; update) {
    // code to be executed
}

Example: Basic for Loop

Let’s consider an example where we use the for loop to print numbers from 1 to 5.

Example Code:

public class ForExample {
    public static void main(String[] args) {
        // Initialize loop control variable i to 1
        // Loop continues as long as i <= 5
        // Increment i by 1 after each iteration
        for (int i = 1; i <= 5; i++) {
            // Print the current value of i
            System.out.println("Count: " + i);
        }
    }
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Use Case: Sum of First n Natural Numbers

Calculate the sum of the first n natural numbers using a for loop.

Example Code:

public class SumExample {
    public static void main(String[] args) {
        int n = 5; // Sum of first 5 natural numbers
        int sum = 0;

        // Loop from 1 to n
        for (int i = 1; i <= n; i++) {
            // Add the current value of i to sum
            sum += i;
        }

        // Print the calculated sum
        System.out.println("Sum of first " + n + " natural numbers is: " + sum);
    }
}

Output:

Sum of first 5 natural numbers is: 15

Use Case: Factorial of a Number

Calculate the factorial of a number using a for loop.

Example Code:

public class FactorialExample {
    public static void main(String[] args) {
        int number = 5; // Factorial of 5
        long factorial = 1;

        // Loop from 1 to the number
        for (int i = 1; i <= number; i++) {
            // Multiply the current value of i with factorial
            factorial *= i;
        }

        // Print the calculated factorial
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

Output:

Factorial of 5 is: 120

Use Case: Enhanced for Loop (for-each Loop)

The enhanced for loop, also known as the for-each loop, is used to iterate over arrays and collections.

Example Code:

public class ForEachExample {
    public static void main(String[] args) {
        // Array of integers
        int[] numbers = {1, 2, 3, 4, 5};

        // Enhanced for loop to iterate over the array
        for (int num : numbers) {
            // Print the current element of the array
            System.out.println("Number: " + num);
        }
    }
}

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Use Case: Nested for Loop

A for loop can be nested inside another for loop. This is useful for iterating over multi-dimensional arrays or performing complex iterations.

Example Code:

public class NestedForExample {
    public static void main(String[] args) {
        // Outer loop iterates from 1 to 3
        for (int i = 1; i <= 3; i++) {
            // Inner loop iterates from 1 to 3
            for (int j = 1; j <= 3; j++) {
                // Print the current values of i and j
                System.out.println("i: " + i + ", j: " + j);
            }
        }
    }
}

Output:

i: 1, j: 1
i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
i: 2, j: 2
i: 2, j: 3
i: 3, j: 1
i: 3, j: 2
i: 3, j: 3

Use Case: Infinite for Loop

A for loop can become an infinite loop if the termination condition is not specified.

Example Code:

public class InfiniteForLoopExample {
    public static void main(String[] args) {
        // Infinite loop with no termination condition
        for (;;) {
            System.out.println("This is an infinite loop");
            // Uncomment the next line to break out of the loop
            // break;
        }
    }
}

Output:

This is an infinite loop
... (continues indefinitely)

Use Case: Using break in for Loop

The break statement can be used to exit the loop prematurely, regardless of the condition.

Example Code:

public class BreakInForLoopExample {
    public static void main(String[] args) {
        // Loop from 1 to 5
        for (int i = 1; i <= 5; i++) {
            // If i equals 3, exit the loop
            if (i == 3) {
                break;
            }
            // Print the current value of i
            System.out.println("Count: " + i);
        }
    }
}

Output:

Count: 1
Count: 2

Use Case: Using continue in for Loop

The continue statement skips the current iteration of the loop and proceeds with the next iteration.

Example Code:

public class ContinueInForLoopExample {
    public static void main(String[] args) {
        // Loop from 1 to 5
        for (int i = 1; i <= 5; i++) {
            // If i equals 3, skip the rest of the loop body
            if (i == 3) {
                continue;
            }
            // Print the current value of i
            System.out.println("Count: " + i);
        }
    }
}

Output:

Count: 1
Count: 2
Count: 4
Count: 5

Conclusion

The for loop is a versatile control flow statement in Java that allows you to iterate over a block of code a specified number of times. By understanding the syntax and various use cases of the for loop, including the basic loop, enhanced for-each loop, nested loop, and how to use break and continue statements, you can write more efficient and flexible Java programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top