Iteration statements

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

Use either Visual Studio 2017 or Visual Studio Code to add a new console application project named Ch03_IterationStatements.

In Visual Studio 2017, you can set the solution's start up project to be the current selection so that the current project runs when you press Ctrl + F5.

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:

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

Run the console application and view the output:

0
1
2
3
4
5
6
7
8
9

The do statement

The do statement is like while, except the Boolean expression is checked at the bottom of the block instead of the top, which means that it always executes at least once.

Type the following code at the end of the Main method and run it:

    string password = string.Empty; 
    do 
    { 
      Write("Enter your password: "); 
      password = ReadLine(); 
    } while (password != "secret"); 
    WriteLine("Correct!"); 

You will be prompted to enter your password repeatedly until you enter it correctly, as shown in the following output:

Enter your password: password
Enter your password: 12345678
Enter your password: ninja
Enter your password: asdfghjkl
Enter your password: secret
Correct!

As an optional exercise, add statements so that the user can only make ten attempts before an error message is displayed.

The for statement

The for statement is like while, except that it is more succinct. It combines an initializer statement that executes once at the start of the loop, a Boolean expression to check whether the loop should continue, and an incrementer that executes at the bottom of the loop. The for statement is commonly used with an integer counter, as shown in the following code:

    for (int y = 1; y <= 10; y++) 
    { 
      WriteLine(y); 
    } 

Run the console application and view the output, which should be the numbers 1 to 10.

The foreach statement

The foreach statement is a bit different from the other three iteration statements. It is used to perform a block of statements on each item in a sequence, for example, an array or collection. Each item is read-only and if the sequence is modified during iteration, for example, by adding or removing an item, then an exception will be thrown.

Type the following code inside the Main method, which creates an array of string variables and then outputs the length each of them:

    string[] names = { "Adam", "Barry", "Charlie" }; 
    foreach (string name in names) 
    { 
      WriteLine($"{name} has {name.Length} characters."); 
    } 

Run the console application and view the output:

Adam has 4 characters.
Barry has 5 characters.
Charlie has 7 characters.

How does the foreach statement work?

Technically, the foreach statement will work on any type that implements an interface called IEnumerable, but you don't need to worry about what an interface is for now.

Note

You will learn about interfaces in Chapter 7, Implementing Interfaces and Inheriting Classes.

The compiler turns the foreach statement in the preceding code into something like this:

    IEnumerator e = names.GetEnumerator(); 
    while (e.MoveNext()) 
    { 
      string name = (string)e.Current; // Current is read-only! 
      WriteLine($"{name} has {name.Length} characters."); 
    } 

Note

Due to the use of an iterator, the variable declared in a foreach statement cannot be used to modify the value of the current item.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.231.194