A for
loop is a control structure that repeats a block of code a specified number of times. It is one of the most commonly used control structures in C#.
If you want to learn more about Loops
check out the Introduction to Programming Course read more
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
}
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 established (generally, it is used to initialize a counter that will be incremented or decremented in each iteration)Condition:
The condition is a boolean expression that is 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 the program continues execution.Update:
In this part of the loop, an action is performed that modifies the value of the variables that control the loop (generally, it is used to increment or decrement the counter)Instructions to execute:
Here, the instructions that are executed in each iteration are specified. These instructions can be any valid code in C# (such as assignments, calculations, method calls, etc.)
Basic Example
Let’s look at a simple example where a for
loop is used to print the numbers from 1 to 10:
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
}
In this example:
- The initialization
int i = 1
sets the initial value ofi
to 1. - The condition
i <= 10
ensures that the loop runs whilei
is less than or equal to 10. - The update
i++
incrementsi
by 1 after each iteration. - Inside the loop, we use the
Console.WriteLine()
method to print the current value ofi
to the console.
The result is that the numbers from 1 to 10 will be displayed on the screen.
Modifying the flow of the loop
Skipping iterations with continue
The continue
statement is used to skip the current iteration and jump 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);
}
Breaking the loop with break
Using the break
statement allows you to exit the loop before the condition is met. This is useful in situations where a specific value is found, and there is no need to continue iterating.
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
Special Cases
It is possible to create more “original” cases of the for
loop. Generally, it is not a good idea to do so. But I mention it, if only so that if you see it someday, 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}");
In this case, i
retains its value after the loop has finished, which will be 5
.
Multiple declarations
In the initialization and update sections, multiple declarations can be included, separated by commas. This is useful when multiple control variables are needed:
for (int i = 0, j = 10; i < j; i++, j--)
{
Console.WriteLine($"i: {i}, j: {j}");
}
Practical Examples
Generating a multiplication table
In this example, a multiplication table is generated for a specific number using a for
loop.
int number = 5; // Number for which the multiplication table is generated
for (int i = 1; i <= 10; i++) // Iterates from 1 to 10
{
Console.WriteLine($"{number} x {i} = {number * i}"); // Prints the multiplication of the number by 'i'
}
Iterating over arrays
One of the most common applications of the for
loop is to iterate over the elements of an array. Here is an example that sums all the elements of an array:
int[] numbers = { 1, 2, 3, 4, 5 }; // Declare the array
int sum = 0; // Variable to store the sum
for (int i = 0; i < numbers.Length; i++)
{
sum += numbers[i]; // Add each element of the array to 'sum'
}
Console.WriteLine($"The sum of the elements is: {sum}");
Iterating with a different step
The value of the update does not always have to be an increment of one. It can be any expression that modifies the control variable. For example, iterating in steps of two:
for (int i = 0; i < 10; i += 2) // Increments 'i' by 2 in each iteration
{
Console.WriteLine(i); // Prints the current value of 'i'
}
Decreasing for loop
You can also use the for
loop to iterate in decreasing order:
for (int i = 10; i > 0; i--) // Decrements 'i' by 1 in each iteration
{
Console.WriteLine(i); // Prints the current value of 'i'
}
Searching for an element in an array
int[] numbers = { 1, 2, 3, 4, 5 }; // Declare the array
int search = 3; // Number to search for
bool found = false; // Variable to indicate if the number was found
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == search) // Compares each element with the searched number
{
found = true; // Marks that the number was found
break; // Exits the loop
}
}
if (found)
{
Console.WriteLine($"The number {search} is found in the array.");
}
else
{
Console.WriteLine($"The number {search} is not found in the array.");
}
These examples are intended to demonstrate how to use the for
loop. It does not mean that it is the best way to solve the problem they address. Usually, there are better alternatives.