Looping means to iterate block of statements over and over based on some condition.C# has several loops based on the requirement.The two main types of loops are the while loop and the for loop.You use the while loop if you want to iterate block of statements based on a boolean condition.On the other hand,you use for loop if you want to loop over statement block based on a condition variable.
Loop variable This is the variable which controls the loop.If the value of this variable is true in the condition block then loop is executed.
If this value is false then the loop exits.We can have multiple loop variables.
There are three important constructs:
- Initialization block this initializes the loop variable and is executed once at the begining.
- Condition or Verification block this should return bool value
- Update block updates the loop variable.this executes after the loop body executes
continue
This statement jumps the execution to next iteration
break
This statement is used to exit from the for loop
Following is the syntax of the for loop:
for(intiailize control variable;boolean condition;update control variable) { //statement block }
The condition is reevaluated after every code block execution and if the condition is false the loop exits.
For example you can use the for loop to iterate from 1 to 15 as:
for(int counter=0;counter<15;counter++) { Console.WriteLine("Hello"); }
All of these blocks(1,2 and 3) are optional.So this is a valid for loop.Though this is not useful as it is an infinite loop.
for ( ; ; ) { //body }
Leave a Reply