Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Foreach loop: Difference between revisions

From Coderwiki
new: info, example, iterating a range
 
m Dylan moved page For each loop to Foreach loop: Misspelled title
 
(No difference)

Latest revision as of 10:22, 15 August 2025

A foreach loop is an iteration structure in code which allows us to loop through a code block for each element in a collection.

It is a form of definite iteration, or count-controlled iteration.

In the below C Sharp code, we loop through the values of the fruits array and print out each element:

string[] fruits = {"Banana", "Apple", "Peach", "Strawberry", "Raspberry"};
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

The code above will give the following output:

Banana
Apple
Peach
Strawberry
Raspberry

Iterating a range of values

edit edit source

If you instead want to loop over a range of integers or another type of range, you should instead use a regular for loop.

See: For loop