Search⌘ K
AI Features

Loops

Explore how to use C# loops such as for, foreach, while, and do...while to repeat code execution while managing conditions. Understand loop control statements break and continue to influence loop behavior and improve program flow.

Loops are constructions that allow us to execute a block of code multiple times until a certain condition is met. We have several types of loops in C#:

  • The for loop

  • The foreach loop

  • The while loop

  • The do...while loop

The for loop

The syntax of the for loop consists of an initialization, a condition, and an iterator.

for (int i = 0; i < 10; i++)
{
// Body of the loop
}
General syntax of a for loop
  • for: The keyword that starts the loop.

  • int i = 0: The initialization statement. It runs once before the loop begins. Here, we create an integer counter i and set it to 0.

  • i < 10: The condition. The loop executes as long as this evaluates to true.

  • i++: The iterator. This executes after every iteration, increasing i by 1.

Though we usually prefer integers, the counter does not have to be of the int type; it can be any numeric type.

Flowchart of a for loop
Flowchart of a for loop

To sum up, the loop declaration above consists of three statements. Before the first iteration of our for loop, we declare and initialize a counter variable, i. Its value is 0 in the beginning. The loop runs as long as i < 10.

Because i increments by one after each iteration, the loop runs exactly 10 times.

We can check this by ...