C# for Loop
In C#, the for
loop is a type of loop statement that is used to execute a block of code repeatedly a specific number of times. The syntax of the for
loop is as follows:
for (initialization; condition; increment) { // Code to execute while the condition is true }
The initialization
expression is evaluated once before the loop starts, and it is typically used to initialize a counter variable. The condition
expression is evaluated at the beginning of each iteration of the loop, and it is used to determine whether the loop should continue executing. The increment
expression is evaluated at the end of each iteration of the loop, and it is typically used to update the counter variable.
Here is an example that uses a for
loop to print the numbers from 1 to 10:
for (int i = 1; i <= 10; i++) { Console.WriteLine(i); }
In this example, the for
loop starts with the initialization expression int i = 1
, which initializes the counter variable i
to 1. The condition
expression i <= 10
tests whether i
is less than or equal to 10. If it is, the code inside the loop is executed, which prints out the value of i
. The increment
expression i++
increments i
by 1 at the end of each iteration. This continues until i
is greater than 10, at which point the loop terminates.
Note that the initialization
, condition
, and increment
expressions are optional, but you must include the semicolons to separate them in the for
loop syntax.