How to use C# for loop
There are many situation when you need to execute a block of statements several number of times in your applications. The for loop in C# is useful for iterating over arrays and for sequential processing. This kind of for loop is useful for iterating over arrays and for other applications in which you know in advance how many times you want the loop to iterate. That is the statements within the code block of a for loop will execute a series of statements as long as a specific condition remains true.
Every for loops defines initializer, condition, and iterator sections.
The for loop initialize the value before the first step. Then checking the condition against the current value of variable and execute the loop statement and then perform the step taken for each execution of loop body.
The initializer declares and initializes a local loop variable, i, that maintains a count of the iterations of the loop. The loop will execute four times because we set the condition i is less than or equal to count.
The output of the code as follows :
C# Sample For loop program full source code
All of the expressions of the for loop statements are optional. A loop becomes infinite loop if a condition never becomes false. You can make an endless loop by leaving the conditional expression empty. The following statement is used to write an infinite loop.
Here the loop will execute infinite times because there is no initialization , condition and steps.
break and continue
We can control for loop iteration with the break and continue statements. break terminates iteration and continue skips to the next iteration cycle. The following program shows a simple example to illustrate break and continue statement.