Collections
Foreach Sum
A foreach loop can aggregate values from a collection.
aggregate
An aggregate calculation combines several values into one result.
Foreach Sum
ForeachSum.cs
Replay: real traced execution (multi-file project)
using System;
class Program
{
static void Main()
{
int bonus = 1;
int[] values = { 2, 4, 6 };
int total = 0;
foreach (int value in values)
{
total += value + bonus;
}
Console.WriteLine($"bonus={bonus}");
Console.WriteLine($"total={total}");
}
}
using System;
class Program
{
static void Main()
{
int bonus = 0;
int[] values = { 2, 4, 6 };
int total = 0;
foreach (int value in values)
{
total += value + bonus;
}
Console.WriteLine($"bonus={bonus}");
Console.WriteLine($"total={total}");
}
}
using System;
class Program
{
static void Main()
{
int bonus = 3;
int[] values = { 2, 4, 6 };
int total = 0;
foreach (int value in values)
{
total += value + 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[] values = { 2, 4, 6 };9 int total→ 0 = 0;total ← 3
pass 1 of 311foreach (int value2 in values)12{13 total→ 3 += value2 + bonus1;14}All 3 passes — pass 1 is the card above pass valuetotal1 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[] values = { 2, 4, 6 };9 int total→ 0 = 0;total ← 2
pass 1 of 311foreach (int value2 in values)12{13 total→ 2 += value2 + bonus0;14}All 3 passes — pass 1 is the card above pass valuetotal1 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[] values = { 2, 4, 6 };9 int total→ 0 = 0;total ← 5
pass 1 of 311foreach (int value2 in values)12{13 total→ 5 += value2 + bonus3;14}All 3 passes — pass 1 is the card above pass valuetotal1 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 Value
- Start
totalat0. - Visit each value in
{ 2, 4, 6 }. - Add the value plus
bonus. - Print the final total after the loop ends.
| Value | Added when bonus is
1| Running total | | --- | --- | --- | |2|3|3| |4|5|8| |6|7|15|
Exercise: ForeachSum.cs
Use foreach to add each value plus a bonus and print the final total