Loops

Learn to execute a block of code multiple times.

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

Let’s explore the syntax of the for loop.

for (int i = 0; i < 10; i++)
{
    // Body of the loop
}

The first statement of the loop declaration (int i = 0) creates and initializes the counter i. Though we usually prefer integers, the counter doesn’t have to be of the int type. It can be any other numeric type.

The first statement runs once before the loop executes. Therefore, it’s a good place to initialize a variable that can be used as a counter for this loop.

The ...