Java for loop Statement with Code Examples

In this blog post, we will delve into the Java for loop statement, providing a detailed explanation along with various code examples to illustrate its usage.

The Basic Syntax of the For Loop

The ‘for loop’ in Java follows a specific syntax that makes it easy to understand and work with. It consists of three parts:

1. Initialization: This part initializes the loop control variable and is executed only once before the loop starts.

2. Condition: The loop will continue executing as long as this condition remains true. It is checked before every iteration.

3. Iteration Expression: This expression is evaluated after each iteration and typically updates the loop control variable.

The general structure of a ‘for loop’ looks like this:

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

Java for loop Code Examples

Now let’s see some code examples using the Java for loop statement:

Printing numbers from 1 to 5

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

In this example, we initialize ‘i’ to 1, set the condition to continue while ‘i’ is less than or equal to 5, and increment ‘i’ by 1 in each iteration. The output will be: 1 2 3 4 5

Computing the sum of the first 10 natural numbers

int sum = 0;
for (int i = 1; i <= 10; i++) {
    sum += i;
}
System.out.println("Sum of the first 10 natural numbers: " + sum);

Here, we initialize ‘sum’ to 0, and in each iteration, we add the current value of ‘i’ to ‘sum’. The output will be: Sum of the first 10 natural numbers: 55

Iterating over an array

int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
    System.out.print(numbers[i] + " ");
}

This example demonstrates how to use the for loop to iterate over an array. The loop control variable ‘i’ is used to access each element of the ‘numbers’ array, printing its content. The output will be: 10 20 30 40 50

Nested for loop to create a pattern

for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print("* ");
    }
    System.out.println();
}

In this example, we use a nested for loop to create a pattern of stars. The outer loop controls the number of rows, and the inner loop controls the number of stars in each row. The output will be:

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

Conclusion

The ‘for loop’ is a powerful and versatile construct in Java, allowing developers to perform repetitive tasks efficiently. Its simple syntax makes it easy to use, while its ability to handle arrays and collections makes it indispensable in many programming scenarios.

In this blog post, we’ve explored the basic syntax of the for loop and provided several code examples to illustrate its functionality.

Happy coding!