Iteration statements

Iteration statements repeat a block either while a condition is true or for each item in a sequence. The choice of which statement to use is based on a combination of ease of understanding to solve the logic problem and personal preference.

Add a new Console Application project named Ch03_IterationStatements.

Set the solution's startup project to be the current selection.

The while statement

The while statement evaluates a Boolean expression and continues to loop while it is true.

Type the following code inside the Main method (remember to statically import the System.Console type!):

int x = 0;
while (x < 10)
{
    WriteLine(x);
    x++;
}

Press Ctrl + F5 and view the output in the console:

0
1
2
3
4
5
6
7
8
9

The do-while statement

The ...

Get C# 6 and .NET Core 1.0: Modern Cross-Platform Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.