Using for Statements in C#


By using a for statement, we can write a more formal version of this kind of construct by combining the initialization, Boolean expression, and code that updates the control variable. We will find the for statement useful because it is much harder to forget any one of the three parts.

Syntax:-

for (initialization; Boolean expression; update control variable)  
    statements

We can rephrase the while loop shown earlier that displays the integers from 0 through 9 as the following for loop:

for (int i = 0; i < 10; i++)  
{  
    Console.WriteLine(i);  
}

The initialization occurs once at the start of the loop. Then, if the Boolean expression evaluates to true, the statement runs. The control variable update occurs, and then the Boolean expression is re-evaluated. If the condition is still true, the statement is executed again, the control variable is updated, the Boolean expression is evaluated again, and so on. Notice that the initialization occurs only once, that the statement in the body of the loop always executes before the update occurs, and that the update occurs before the Boolean expression reevaluates. We can omit any of the three parts of a for statement. If we omit the Boolean expression, it defaults to true.

The following for statement runs forever:

for (int i = 0; ;i++)  
{  
    Console.WriteLine("i can't stop myself.");
}

If we omit the initialization and update parts, we have a strangely spelled while loop:

int i = 0;  
for (; i < 10; )  
{  
    Console.WriteLine(i);  
    i++;  
}

If necessary, we can provide multiple initializations and multiple updates in a for loop  (We can have only one Boolean expression ). To achieve this, separate the various initializations and updates with commas, as shown in the following example:

for (int i = 0, j = 10; i <= j; i++, j--)  
{  
    ...  
}

Comments

Popular posts from this blog

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples