csharp-bucle-for

What is and how to use the FOR loop

  • 6 min

A for loop is a control structure that repeats a block of code a specific number of times. It is one of the most used control structures in C#.

If you want to learn more, check out the Introduction to Programming Course

Basic Syntax

The syntax of a for loop in C# consists of three main parts: initialization, condition, and update. These parts are specified within the parentheses of the for loop and are separated by semicolons.

The basic structure of a for loop in C# is as follows:

for (initialization; condition; update)
{
    // Instructions to execute in each iteration
}
Copied!

Let’s look at each of the parts:

  • Initialization: In this part of the loop, the initial values of the variables that will control the loop’s execution are set (usually used to initialize a counter that will be incremented or decremented in each iteration)

  • Condition: The condition is a boolean expression evaluated before each iteration. If the condition is true, the instructions inside the loop are executed. If the condition is false, the loop is exited and program execution continues

  • Update: In this part of the loop, an action is performed that modifies the value of the variables controlling the loop (usually used to increment or decrement the counter)

  • Instructions to execute: Here, the instructions executed in each iteration are specified. These instructions can be any valid C# code (such as assignments, calculations, method calls, etc.)

Basic Example

Let’s see a simple example where a for loop is used to print numbers from 1 to 10:

for (int i = 1; i <= 10; i++)
{
    Console.WriteLine(i);
}
Copied!

In this example:

  • The initialization int i = 1 sets the initial value of i to 1.
  • The condition i <= 10 ensures the loop executes while i is less than or equal to 10.
  • The update i++ increments i by 1 after each iteration.
  • Inside the loop, we use the Console.WriteLine() method to print the current value of i to the console.

The result is that numbers from 1 to 10 will be displayed on the screen.

Modifying Loop Flow

Skipping Iterations with continue

The continue statement is used to skip the current iteration and move directly to the next iteration of the loop.

for (int i = 0; i < 10; i++)
{
    if (i % 2 == 0)
    {
        continue; // Skip even numbers
    }
    Console.WriteLine(i);
}
Copied!

Breaking the Loop with break

Using the break statement allows exiting the loop before the condition is met. This is useful in situations where a specific value is found and there’s no need to continue iterating.

for (int i = 0; i < 10; i++)
{
    if (i == 5)
    {
        break;
    }
    Console.WriteLine(i);
}
Copied!

Special Cases

It is possible to create more “original” cases of the For loop. In general, it’s not a good idea to do so. But I’m telling you, if only so that if you ever see it, you can scold someone. 😉

Using External Variables

It is possible to use a variable declared outside the for loop as the control variable. However, this can lead to confusion and errors if not managed properly:

int i = 0;
for (i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}
Console.WriteLine($"Value of i after the loop: {i}");
Copied!

In this case, i retains its value after the loop has finished, which will be 5.

Multiple Declarations

In the initialization and update sections, you can include multiple statements separated by commas. This is useful when you need several control variables:

for (int i = 0, j = 10; i < j; i++, j--)
{
    Console.WriteLine($"i: {i}, j: {j}");
}
Copied!

Practical Examples

These examples are intended to show how to use the For loop. It does not mean it’s the best way to solve the problem they address. Usually, there are better alternatives.