📜  for loop cs - C# (1)

📅  最后修改于: 2023-12-03 15:15:10.032000             🧑  作者: Mango

For Loop in C#

For Loop is one of the most commonly used loops in C#. It is used when we want to execute a set of statements a specific number of times. The syntax of the for loop is as follows:

for(initialization; condition; increment/decrement)
{
    //Statements to be executed
}
  • initialization - This statement is executed before the loop starts. It is used to initialize the loop counter.
  • condition - This statement is tested before each iteration of the loop. If it is true, the loop continues. If it is false, the loop terminates.
  • increment/decrement - This statement is executed after each iteration of the loop. It is used to increment or decrement the loop counter.

Here is an example:

for(int i=0; i<10; i++)
{
    Console.WriteLine("Loop Counter: {0}", i);
}

The above code will output the loop counter from 0 to 9.

Nested For Loop

A nested for loop is simply a loop inside another loop. It is used to iterate over a two-dimensional array. The syntax of the nested for loop is as follows:

for(int i=0; i<size1; i++)
{
    for(int j=0; j<size2; j++)
    {
        //Statements to be executed
    }
}

Here, size1 and size2 are the sizes of the two-dimensional array.

Here is an example:

int[,] arr = new int[3, 2]{{1, 2}, {3, 4}, {5, 6}};

for(int i=0; i<3; i++)
{
    for(int j=0; j<2; j++)
    {
        Console.WriteLine("Array Element [{0},{1}]: {2}", i, j, arr[i,j]);
    }
}

The above code will output the elements of the two-dimensional array arr.

Conclusion

For loop is a powerful construct in C# used to execute a set of statements a specific number of times. It is widely used in programming and is essential for any developer to understand.