Looping Statements in C#
C# has four looping statements: while, do-while, for and for each. Each of them provides ways for you to specify that a group of statements should be executed until some condition is satisfied.
The while Loop
The while loop is easy to understand. All of the statements inside the braces are executed repeated as long as the condition is true.
i = 0;
while ( i < 100)
{
x = x + i++;
}
Since the loop is executed as long as the condition is true, it is possible that such a loop may never be executed at all, and of course, if you are not careful, that such a while loop will never be completed.
The do-while Statement
The C# do-while statement is quite analogous, except that in this case the loop must always be executed at least once, since the test is at the bottom of the loop:
i = 0;
do {
x += i++;
}
while (i < 100);
The for Loop
The for loop is the most structured. It has three parts: an initializer, a condition, and an operation that takes place each time through the loop.
Each of these sections are separated by semicolons:
for (i = 0; i< 100; i++) {
x += i;
}
Let's take this statement apart:
for (i = 0; //initialize i to 0
i < 100 ; //continue as long as i < 100

Join the conversation! Your thoughts help the community grow.