Develop programs to demonstrate use of Looping Statement 'for' in Java

Java Looping Statements: 


This article introduces the 'for' loop in Java, explaining its syntax and how it is used for iterative tasks. It provides examples and discusses common use cases.

Code:

public class ForLoopDemo {
    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


Looping Through Arrays Using 'for' Loops in Java:

public class ArrayIterationDemo {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        System.out.println("Iterating through a one-dimensional array:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Element at index " + i + ": " + numbers[i]);
        }
    }
}

Output: 
Iterating through a one-dimensional array:
Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5


Nested 'for' Loops for Patterns in Java

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

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

Output:
Pattern 1:
* * 
* * * 
* * * * 
* * * * * 




Comments