Open In App

Java Program to Iterate Over Arrays Using for and for-each Loop

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, arrays are a collection of elements of the same type. To access and manipulate elements, we can use iteration techniques such as the for loop and for-each loop (also known as the enhanced for loop).

Program to Iterate Over Arrays Using for and for-each Loop in Java

In the below example, we will demonstrate how to iterate through an array using both the traditional for loop and the simplified for-each loop.

Example:

Java
// Java program to iterate over an array 
// using for loop and for-each loop
public class Loop {
  
    public static void main(String[] args) {
      
        int[] n = {1, 2, 3, 4, 5};

        // Using for loop
        System.out.println("Using for loop:");
        for (int i = 0; i < n.length; i++) {
            System.out.println(n[i]);
        }

        // Using for-each loop
        System.out.println("Using for-each loop:");
        for (int num : n) {
            System.out.println(num);
        }
    }
}

Output
Using for loop:
1
2
3
4
5
Using for-each loop:
1
2
3
4
5

Explanation: Here, both loops print the same array elements, but the for-each loop simplifies the iteration by eliminating the need for an index.



Next Article
Article Tags :
Practice Tags :

Similar Reads