Loops and Iteration
Use for, foreach, and while loops safely.
Introduction
C# offers several loop forms so iteration can express either indexes, values, or a changing condition.
foreach avoids manual indexes when only values are needed. continue skips the current item without ending the loop.
See how it works
Press Step to run the loop one move at a time. Watch the condition being checked, the body running and the trace table growing row by row.
Runnable C# example
Program.cs
using System;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6 };
foreach (int number in numbers)
{
if (number % 2 != 0) continue;
Console.WriteLine(number * number);
}
}
}
4
16
36Practice with the debugger
Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Sum of Odd Numbers Add every odd number up to a limit. Easy
- Countdown to Liftoff Count down from a number and end with Liftoff! Easy