The for Loop

The for Loop

The for loop in C# is a commonly used loop that allows you to execute a block of code a specified number of times. It has the following syntax:

for (initialization; condition; increment)

{

    // code to execute

}

The initialization statement is used to declare and initialize a loop variable, typically an integer that serves as a counter for the number of times the loop should run. The condition statement is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the loop will continue to execute. If the condition is false, the loop will terminate. The increment statement is used to modify the loop variable after each iteration of the loop.

Here is an example of a for loop that prints the numbers from 1 to 10:

for (int i = 1; i <= 10; i++)

{

    Console.WriteLine(i);

}

In this example, the loop starts with i set to 1. The condition statement checks if i is less than or equal to 10. If the condition is true, the loop continues to execute. The increment statement increments i by 1 after each iteration of the loop. The loop terminates after the 10th iteration.

You can also use nested for loops to perform more complex tasks. For example, the following code prints a multiplication table:

for (int i = 1; i <= 10; i++)

{

    for (int j = 1; j <= 10; j++)

    {

        Console.Write(“{0} “, i * j);

    }

    Console.WriteLine();

}

In this example, there are two for loops. The outer loop iterates over the rows of the multiplication table, and the inner loop iterates over the columns. The Console.Write method is used to print each value in the table, and the Console.WriteLine method is used to move to the next row after each iteration of the outer loop.

The for loop is a powerful tool in C# that can be used to execute a block of code a specified number of times. By combining for loops with conditional statements, you can write programs that can handle a wide range of tasks, from simple arithmetic operations to complex data processing.

Apply for ASP.NET Certification Now!!

https://www.vskills.in/certification/certified-aspnet-programmer

Back to Tutorial

Share this post
[social_warfare]
Loops
The foreach loop

Get industry recognized certification – Contact us

keyboard_arrow_up