C# For and Foreach Loops
Use for when the position matters and foreach when you only need each existing value.
How it works
A for loop puts initialization, continuation and update together. Its condition is checked before the body, allowing an empty traversal. foreach expresses a visit to each element without manual index arithmetic. Pick the form from the operation rather than treating one as universally better. When an algorithm changes a collection’s structure, ordinary enumeration may be invalidated; build a separate result or use an operation designed for removal.
Run it locally
Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-buildUse the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.
Example
using System;
internal static class Program
{
private static void Main(string[] args)
{
for (int table = 1; table <= 3; table++) Console.WriteLine($"Table {table}");
int[] places = { 2, 4, 3 };
int total = 0;
foreach (int count in places) total += count;
Console.WriteLine($"Total: {total}");
}
}
Expected result
Table 1
Table 2
Table 3
Total: 9
The first loop prints one-based labels. The second uses stored values directly and sums a small bounded fixture. An array’s valid indices run from zero through Length minus one. A loop using index <= Length adds an invalid iteration. Keep a total’s range in mind when the input is no longer a fixed small array.
Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.