Java For Loop

Welcome to The Coding College! In this tutorial, we’ll dive into the for loop in Java, a powerful control structure for iterating over a range of values or conditions. The for loop is often preferred when the number of iterations is known beforehand.

Syntax of the for Loop

for (initialization; condition; update) {
    // Code to be executed
}
  • initialization: Initializes the loop variable.
  • condition: Evaluated before each iteration; the loop runs while this evaluates to true.
  • update: Updates the loop variable after each iteration.

Basic Example: Print Numbers from 1 to 5

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

Output:

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

Nested for Loop

You can place one for loop inside another to handle multi-dimensional data or complex patterns.

Example: Print a 3×3 Matrix

public class NestedForLoop {
    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)

Examples of the for Loop

Example 1: Sum of First 10 Natural Numbers

public class SumOfNumbers {
    public static void main(String[] args) {
        int sum = 0;

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

        System.out.println("Sum of first 10 natural numbers: " + sum);
    }
}

Output:

Sum of first 10 natural numbers: 55

Example 2: Reverse a String

public class ReverseString {
    public static void main(String[] args) {
        String str = "Hello";
        String reversed = "";

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

        System.out.println("Reversed string: " + reversed);
    }
}

Output:

Reversed string: olleH

Example 3: Print Multiplication Table

public class MultiplicationTable {
    public static void main(String[] args) {
        int number = 5;

        for (int i = 1; i <= 10; i++) {
            System.out.println(number + " x " + i + " = " + (number * i));
        }
    }
}

Output:

5 x 1 = 5  
5 x 2 = 10  
...  
5 x 10 = 50

Example 4: Infinite Loop

public class InfiniteForLoop {
    public static void main(String[] args) {
        for (;;) { // No initialization, condition, or update
            System.out.println("This is an infinite loop.");
            break; // Use this to exit the loop
        }
    }
}

Example 5: Loop with Multiple Variables

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

Output:

i = 1, j = 5  
i = 2, j = 4  
i = 3, j = 3

Example 6: Skipping Iterations

Use the continue keyword to skip specific iterations.

public class SkipIteration {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue; // Skip the rest of the loop when i is 3
            }
            System.out.println("Number: " + i);
        }
    }
}

Output:

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

Practice Problems

  1. Write a program to find the factorial of a number using a for loop.
  2. Create a program to print all even numbers between 1 and 50.
  3. Use a nested for loop to generate a pyramid pattern of stars (*).

Conclusion

The for loop is a versatile tool in Java programming, ideal for tasks where the number of iterations is predetermined. By mastering its use, you can simplify complex problems and write efficient code.

For more Java tutorials, examples, and practice problems, visit The Coding College. Happy learning! 🚀

Leave a Comment