Slide 1
Slide 2
Slide 3

Array with for loop and for-each in java programming (V45)

No Comments

Iterating Through Arrays
 

Iterating through arrays is a common task in Java. It is the process of traversing each element one by one.

There are two main ways to iterate through arrays:

  1. Using a for loop

  2. Using a for-each loop

for Loop Syntax:

Source Code:

Copied!
public class ForLoopArray {
    public static void main(String[] args) {
        // Declare and initialize an array of integers
        int[] numbers = {10, 20, 30, 40, 50};

        // Using a for loop to iterate through the array
        System.out.println("Array elements:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Element at index " + i + ": " + numbers[i]);
        }
    }
}

Result:

Ø  for-each Loop Syntax:

Source Code:

Copied!
public class ForEach {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Cherry", "Mango"};

        for (String fruit : fruits) {
            System.out.println("Fruit: " + fruit);
        }
    }
}

Result:

Watch the video:


Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

back to top