while repeats as long as a condition holds — use it when the number of passes is not known up front.
Program.cs
using System;
class Program
{
static void Main()
{
int countdown = 3;
while (countdown > 0)
{
Console.WriteLine(countdown);
countdown--;
}
Console.WriteLine("Go");
}
}
Output
3 2 1 Go
More often you want to accumulate into a variable declared outside the loop:
Program.cs
using System;
class Program
{
static void Main()
{
int total = 0;
for (int i = 1; i <= 5; i++)
{
total += i;
}
Console.WriteLine($"Total: {total}");
}
}
Output
Total: 15
Declare the accumulator outside
Something declared inside the loop is created fresh on every pass. To carry a value across passes it has to live outside.