c-plus-plus
  1. c-plus-plus-foreach-in-c-and-java

Foreach in C++ and Java

Foreach is a looping construct that allows you to iterate over the elements of an array or collection without having to worry about the underlying implementation details. It is available in multiple programming languages including C++ and Java.

Foreach in C++

The foreach loop in C++ is known as "range-based for loop" and it allows you to iterate over the elements of an array or container by value or by reference.

Syntax

for (variable : array) {
    // code
}

Example

#include <iostream>
using namespace std;

int main() {
    int arr[] {1, 2, 3, 4, 5};

    // iterate over array elements by value
    for (int i : arr) {
        cout << i << " ";
    }

    // iterate over array elements by reference
    for (int& i : arr) {
        i = i * i;
    }

    cout << endl;

    // iterate over array elements to verify
    for (int i : arr) {
        cout << i << " ";
    }

    return 0;
}

Output

1 2 3 4 5
1 4 9 16 25

Explanation

In the above example, we have defined an integer array called "arr" and used the range-based for loop to iterate over its elements by value and by reference. We have also squared the elements of the array by modifying them using a reference.

Use

The range-based for loop is useful when you need to process every element of an array or container, without having to worry about its underlying implementation.

Important Points

  • The range-based for loop was introduced in C++11.
  • It provides a simple and efficient way to iterate over array elements or containers.
  • The loop variable can be declared either by value or by reference.
  • The loop variable can be modified inside the loop if declared by reference.

Foreach in Java

The foreach loop in Java is known as "enhanced for loop" and it allows you to iterate over the elements of an array or collection.

Syntax

for (variable : array) {
    // code
}

Example

import java.util.ArrayList;
import java.util.List;

public class ForeachExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Hello");
        list.add("World");
        list.add("!");

        for (String str : list) {
            System.out.print(str + " ");
        }
    }
}

Output

Hello World !

Explanation

In the above example, we have defined an ArrayList called "list" and used the enhanced for loop to iterate over its elements.

Use

The enhanced for loop is useful when you need to process every element of an array or collection.

Important Points

  • The enhanced for loop was introduced in Java 5.
  • It provides a clean and concise way to iterate over array elements or collections.
  • The loop variable is always declared by value and cannot be modified inside the loop.
Published on: