Foundations
Loops
Loops repeat a block while a counter changes.
for loop
A `for` loop can initialize a counter, test a condition, and update the counter after each pass.
Loops
Loops.cs
Replay: real traced execution (multi-file project)
using System;
class Program
{
static void Main()
{
int limit = 4;
int total = 0;
for (int number = 1; number <= limit; number++)
{
total += number;
}
Console.WriteLine($"limit={limit}");
Console.WriteLine($"total={total}");
}
}
using System;
class Program
{
static void Main()
{
int limit = 2;
int total = 0;
for (int number = 1; number <= limit; number++)
{
total += number;
}
Console.WriteLine($"limit={limit}");
Console.WriteLine($"total={total}");
}
}
using System;
class Program
{
static void Main()
{
int limit = 6;
int total = 0;
for (int number = 1; number <= limit; number++)
{
total += number;
}
Console.WriteLine($"limit={limit}");
Console.WriteLine($"total={total}");
}
}
limit ← 4, total ← 0
4{5 static void Main()6 {7 int limit→ 4 = 4; //@limit=2, 68 int total→ 0 = 0;total ← 1
pass 1 of 410for (int number1 = 1; number <= limit4; number++)11{12 total→ 1 += number1;13}All 4 passes — pass 1 is the card above pass numbertotal1 1 1 2 2 3 3 3 6 4 4 10 Console.WriteLine($"limit={limit}");
15 Console.WriteLine($"limit={limit4}");16 Console.WriteLine($"total={total10}");17}outputlimit=4 total=10
limit ← 2, total ← 0
4{5 static void Main()6 {7 int limit→ 2 = 2;8 int total→ 0 = 0;total ← 1
pass 1 of 210for (int number1 = 1; number <= limit2; number++)11{12 total→ 1 += number1;13}total ← 3
pass 2 of 210for (int number2 = 1; number <= limit2; number++)11{12 total→ 3 += number2;13}Console.WriteLine($"limit={limit}");
15 Console.WriteLine($"limit={limit2}");16 Console.WriteLine($"total={total3}");17}outputlimit=2 total=3
limit ← 6, total ← 0
4{5 static void Main()6 {7 int limit→ 6 = 6;8 int total→ 0 = 0;total ← 1
pass 1 of 610for (int number1 = 1; number <= limit6; number++)11{12 total→ 1 += number1;13}All 6 passes — pass 1 is the card above pass numbertotal1 1 1 2 2 3 3 3 6 4 4 10 5 5 15 6 6 21 Console.WriteLine($"limit={limit}");
15 Console.WriteLine($"limit={limit6}");16 Console.WriteLine($"total={total21}");17}outputlimit=6 total=21
Follow the Loop
limitstarts at4.totalstarts at0.- The loop adds
1, then2, then3, then4. totalbecomes10.- The program prints
limit=4andtotal=10. | limit | numbers added | total | | --- | --- | --- | | 2 | 1, 2 | 3 | | 4 | 1, 2, 3, 4 | 10 | | 6 | 1, 2, 3, 4, 5, 6 | 21 |
Exercise: Loops.cs
Reproduce total=10 for limit 4, then use the pinned limits 2 and 6 to predict each total.