C# for Loop Statements

A for loop is used in C# to iterate over a block of code a specific number of times. It provides a simple and concise way to loop through arrays, collections, and other types of data structures.

The basic syntax of a for loop is as follows:

1for (initialization; condition; increment) 2{ 3 // code to be executed 4}

The initialization section is used to declare and initialize the loop variable, which is typically an integer. The condition section is a boolean expression that is evaluated at the beginning of each iteration of the loop. If the condition is true, the loop continues to execute. If the condition is false, the loop is terminated. The increment section is used to update the loop variable at the end of each iteration.

Let's look at an example to see how a for loop works:

1for (int i = 1; i <= 5; i++) 2{ 3 Console.WriteLine("The value of i is: " + i); 4}

In this example, the loop variable i is initialized to 1. The loop will continue to execute as long as i is less than or equal to 5. At the end of each iteration, i is incremented by 1. The output of this code will be:

1The value of i is: 1 2The value of i is: 2 3The value of i is: 3 4The value of i is: 4 5The value of i is: 5

Using for loops with arrays

One of the most common uses of a for loop in C# is to iterate over an array. Let's take a look at an example:

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

In this example, we create an array of integers called numbers. We then use a for loop to iterate over the array and print out each element. The loop variable i is initialized to 0, and the loop will continue to execute as long as i is less than the length of the array. At the end of each iteration, i is incremented by 1.

The output of this code will be:

11 22 33 44 55

Using nested for loops

It is also possible to use nested for loops in C# to iterate over multiple arrays or other data structures. Let's take a look at an example:

1int[,] matrix = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; 2 3for (int i = 0; i < matrix.GetLength(0); i++) 4{ 5 for (int j = 0; j < matrix.GetLength(1); j++) 6 { 7 Console.Write(matrix[i, j] + " "); 8 } 9 10 Console.WriteLine(); 11}

In this example, we create a two-dimensional array called matrix. We use nested for loops to iterate over the array and print out each element. The outer loop iterates over the rows of the matrix, while the inner loop iterates over the columns. The GetLength() method is used to determine the size of each dimension of the array.

The output of this code will be:

11 2 23 4 35 6