Java For Loop -

Java For Loop

A for loop in Java is a control flow statement that repeats a block of code for a fixed number of iterations. This is useful when you know in advance how many times you need to execute a statement or a block of statements.


Definition

The for loop allows you to execute a block of code multiple times by setting an initial value, a condition to check, and an update to the loop variable.


Syntax

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

Components of a For Loop

  1. Initialization: Sets the starting value of the loop control variable (e.g., int i = 0).
  2. Condition: Defines the termination condition; the loop runs as long as this condition is true.
  3. Update: Changes the loop variable after each iteration (e.g., i++).

Example 1: Simple For Loop

public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Iteration: " + i);
        }
    }
}

Output:

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

How It Works

  1. Initialization: int i = 1 sets i to 1.
  2. Condition: i <= 5 checks if i is less than or equal to 5.
  3. Update: i++ increments i by 1 after each iteration.

Example 2: For Loop with an Array

public class ArrayLoop {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};

        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Element: " + numbers[i]);
        }
    }
}

Output:

Element: 10  
Element: 20  
Element: 30  
Element: 40  
Element: 50  

Nested For Loops

You can use one for loop inside another to work with more complex problems, such as printing patterns.

public class NestedLoop {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.print(i + "," + j + " ");
            }
            System.out.println();
        }
    }
}

Output:

1,1 1,2 1,3  
2,1 2,2 2,3  
3,1 3,2 3,3  

Infinite Loop

A for loop can run infinitely if you omit the termination condition or never update the loop variable properly.

for (;;) {
    System.out.println("This is an infinite loop");
}

Note: Avoid infinite loops unless absolutely necessary.


Conclusion

The for loop is a fundamental control structure in Java, helping to simplify repetitive tasks. Whether iterating over numbers, arrays, or patterns, it ensures clean and efficient code. For more tips and examples, visit Master Coding Science at mastercodingscience.com.

Leave a Comment