For Loops

Lesson 20
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

In C#, a for loop is a control flow statement that allows you to execute a block of code repeatedly for a specified number of times. It is often used when you know the exact number of iterations you want to perform.

The syntax for a for loop in C# is as follows:

for (initialization; condition; increment)
{
    // code to be executed
}

Here’s what each part of the for loop means:

initialization: This is where you initialize the loop counter variable to a starting value. It is executed only once, before the loop starts.

condition: This is the condition that is checked before each iteration of the loop. If it evaluates to true, the loop continues; if it evaluates to false, the loop exits.

increment: This is the operation that is performed after each iteration of the loop. It is typically used to increment or decrement the loop counter variable.

code to be executed: This is the block of code that will be executed repeatedly for the specified number of iterations.

Here’s an example of using a for loop to print the numbers 1 through 5:

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine(i);
}

In this example, we’ve initialized the loop counter variable i to 1, set the condition to i <= 5, and used the increment operator i++ to increment the loop counter variable by 1 after each iteration. The code inside the loop simply prints the value of i to the console.

The output of this program would be:

1
2
3
4
5

You can also use a for loop to iterate over an array:

int[] numbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}

In this example, we’ve declared an integer array called numbers with five elements. We’ve used the numbers.Length property to set the condition for the loop, which will continue until the loop counter variable i is equal to numbers.Length - 1. The code inside the loop simply prints the value of the array element at index i to the console.

The output of this program would be:

1
2
3
4
5