Loop constructs – for each

Loop constructs – for each

The for-each loop, also known as the for-in loop, is a variation of the for loop in programming languages that allows you to iterate over the elements of a collection or an iterable object one at a time, without the need for an index variable.

The syntax of the for-each loop varies slightly depending on the programming language, but the basic structure is as follows:

for element in collection:
# code to execute for each element in the collection

In this syntax, element is a variable that takes on the value of each element in the collection one at a time, and the block of code inside the loop is executed for each value of element.

Here is an example of a for-each loop in Java that prints the elements of an array:

int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}

In this example, the for loop iterates over each element in the numbers array, assigning it to the num variable one at a time. The System.out.println(num) statement inside the loop prints the value of num for each iteration of the loop.

The for-each loop can be used to iterate over many different types of collections, including arrays, lists, and sets, as well as other types of iterable objects. It is a convenient and concise way to iterate over a collection without the need for an index variable, making your code more readable and easier to understand.

Apply for PHP Certification!

https://www.vskills.in/certification/certified-php-developer

Back to Tutorials

AutoFill
Viewing Options

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?