C# For Each Loop
A foreach loop runs a block once for each item in an array. Each run puts the next item in a loop variable.
Print each item
The loop runs once for each number. The variable num holds the current number on each run.
using System;
class Program
{
static void Main(string[] args)
{
int[] nums = { 4, 7, 9 };
foreach (int num in nums)
{
Console.WriteLine(num);
}
}
}Sort then print
Array.Sort puts the numbers in order. The foreach loop then prints the sorted order.
using System;
class Program
{
static void Main(string[] args)
{
int[] nums = { 9, 2, 5 };
Array.Sort(nums);
foreach (int num in nums)
{
Console.WriteLine(num);
}
}
}Add with foreach
The loop adds each number to total. The final total prints after the loop ends.
using System;
class Program
{
static void Main(string[] args)
{
int[] nums = { 2, 3, 4 };
int total = 0;
foreach (int num in nums)
{
total += num;
}
Console.WriteLine(total);
}
}Join into one string
string.Join places a separator between items. The joined string prints on one line.
using System;
class Program
{
static void Main(string[] args)
{
int[] nums = { 3, 1, 2 };
Console.WriteLine(string.Join(", ", nums));
}
}Example
using System;
class Program
{
static void Main(string[] args)
{
int[] scores = { 85, 72, 90, 68 };
Array.Sort(scores);
foreach (int score in scores)
{
Console.WriteLine(score);
}
}
}Key points
- The foreach keyword starts a foreach loop.
- The loop variable holds one item on each run.
- A foreach loop needs no index and no counter.
- Array.Sort puts the items of an array in order.
- Use string.Join to join array items into one string.
In this example, scores holds four test scores in no set order. Array.Sort puts the scores in order from smallest to largest. The foreach loop prints 68 first. It then prints 72, 85, and 90 in order.
Note
A foreach loop gives no index for the current item.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
Exercise
What does a foreach loop do with an array?