Control Flow
Foreach Loops
A foreach loop visits each item in a collection.
foreach
A foreach loop assigns each item to a loop variable for one pass through the block.
Foreach Loops
ForeachLoop.cs
Replay: real traced execution (multi-file project)
using System;
class Program
{
static void Main()
{
int bonus = 1;
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 = 0;
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 = 3;
int[] scores = { 2, 4, 6 };
int total = 0;
foreach (int score in scores)
{
total += score + bonus;
}
Console.WriteLine($"bonus={bonus}");
Console.WriteLine($"total={total}");
}
}
bonus ← 1, total ← 0
4{5 static void Main()6 {7 int bonus→ 1 = 1; //@bonus=0, 38 int[] scores = { 2, 4, 6 };9 int total→ 0 = 0;total ← 3
pass 1 of 311foreach (int score2 in scores)12{13 total→ 3 += score2 + bonus1;14}All 3 passes — pass 1 is the card above pass scoretotal1 2 3 2 4 8 3 6 15 Console.WriteLine($"bonus={bonus}");
16 Console.WriteLine($"bonus={bonus1}");17 Console.WriteLine($"total={total15}");18}outputbonus=1 total=15
bonus ← 0, total ← 0
4{5 static void Main()6 {7 int bonus→ 0 = 0;8 int[] scores = { 2, 4, 6 };9 int total→ 0 = 0;total ← 2
pass 1 of 311foreach (int score2 in scores)12{13 total→ 2 += score2 + bonus0;14}All 3 passes — pass 1 is the card above pass scoretotal1 2 2 2 4 6 3 6 12 Console.WriteLine($"bonus={bonus}");
16 Console.WriteLine($"bonus={bonus0}");17 Console.WriteLine($"total={total12}");18}outputbonus=0 total=12
bonus ← 3, total ← 0
4{5 static void Main()6 {7 int bonus→ 3 = 3;8 int[] scores = { 2, 4, 6 };9 int total→ 0 = 0;total ← 5
pass 1 of 311foreach (int score2 in scores)12{13 total→ 5 += score2 + bonus3;14}All 3 passes — pass 1 is the card above pass scoretotal1 2 5 2 4 12 3 6 21 Console.WriteLine($"bonus={bonus}");
16 Console.WriteLine($"bonus={bonus3}");17 Console.WriteLine($"total={total21}");18}outputbonus=3 total=21
Add Each Score
bonusstarts at1.- The scores are
2,4, and6. - Each pass adds the score plus the bonus.
- The final total is
15. | Score | Added with bonus1| Running total | | --- | --- | --- | |2|3|3| |4|5|8| |6|7|15|
Exercise: ForeachLoop.cs
Use foreach to add each score plus a bonus and print the total