Explain For-each Loop
The foreach loop, also known as a for-each loop, is a control flow statement used in programming languages to iterate over elements in a collection, such as an array, list, or other iterable data structures. It provides an easy and concise way to access each element within the collection without the need for explicit indexing or managing loop counters.
The foreach loop is designed to simplify iteration and improve code readability. It abstracts away the details of accessing individual elements, allowing you to focus on processing the elements themselves.
The general syntax of a foreach loop is as follows:
for (element_type element : collection) { // Code block to be executed for each element }
Here’s how the foreach loop works:
- The loop variable,
element
, is declared with a specific type that matches the type of elements in the collection. - The loop iterates over each element in the
collection
. - For each iteration, the loop variable
element
is assigned the value of the current element in the collection. - The code block within the loop is executed for each element, allowing you to perform operations or computations on that element.
- After executing the code block, the loop proceeds to the next element in the collection.
- The loop continues until all elements in the collection have been processed.
- Once all elements have been iterated over, the loop terminates, and the program continues with the next statement after the loop.
The foreach loop eliminates the need for manual management of loop indices or iterators, reducing the potential for off-by-one errors and making the code more concise and readable.
C++ Example
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
cout << number << " ";
}
return 0;
}
Output
1 2 3 4 5
Java Example
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
for (int number : numbers) {
System.out.print(number + " ");
}
}
}
Output
1 2 3 4 5
Python Example
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number, end=' ')
Output
1 2 3 4 5
JavaScript Example
const numbers = [1, 2, 3, 4, 5]; for (const number of numbers) { console.log(number); }
Output
1
2
3
4
5