Control Flow
Foreach Loops
A foreach loop visits each item in a collection.
Foreach Loops
ForeachLoop.cs
using System;
class Program
{
static void Main()
{
int bonus = ;
int[] scores = { 2, 4, 6 };
int total = 0;
foreach (int score in scores)
{
total += score + bonus;
}
Console.WriteLine($"bonus={bonus}");
Console.WriteLine($"total={total}");
}
}
using System;
class Program
{
static void Main()
{
int bonus = ;
int[] scores = { 2, 4, 6 };
int total = 0;
foreach (int score in scores)
{
total += score + bonus;
}
Console.WriteLine($"bonus={bonus}");
Console.WriteLine($"total={total}");
}
}
using System;
class Program
{
static void Main()
{
int bonus = ;
int[] scores = { 2, 4, 6 };
int total = 0;
foreach (int score in scores)
{
total += score + bonus;
}
Console.WriteLine($"bonus={bonus}");
Console.WriteLine($"total={total}");
}
}
foreach
A foreach loop assigns each item to a loop variable for one pass through the block.