C # Tutorial Lesson Four: Circular control statements

Source: Internet
Author: User
Tags foreach continue expression readline
Tutorials | control | loops | Statements This section describes how to use the looping statements in C # control statements, as follows in this lesson:
1. Learn the use of "while" loops.

2. Learn the use of "do" loops.

3. Learn the use of "for" loops.

4. Learn the use of a foreach loop.

5. Learn more about the use of the "break" statement.

6. How to use the "continue" statement.

In C #, using the goto statement is not the best way to build a loop. This lesson will describe the common ways to build loops.

The first statement to introduce is the while loop statement

1. Listing 4-1. While loop: While Loop.cs

Using System;
Class Whileloop {
public static void Main () {
int myInt = 0;

while (MyInt < 10) {
Console.Write ("{0}", myInt);
myint++;
}
Console.WriteLine ();
}
}

Description

1. Listing 4-1 illustrates a simple while loop.

Begins with the keyword "while" followed by a Boolean expression. All control statements Use Boolean expressions. This means that the expression must calculate a value of true or false. In this case, we'll examine the myint variable to see if it's less than 10. Because Myint has been initialized to 0, the Boolean expression returns a True value the first time it is evaluated. Once the Boolean expression evaluates to True, the statement in the block following the Boolean expression is executed.

2. In the while block, we output the number and space to the console, and then add the myint to the 1 operation. Once the statement in the while block is executed, the value of the Boolean expression is evaluated again, and this continues until the Boolean expression evaluates to False. Once the Boolean expression evaluates to False, the program starts execution from the first statement after the while block. In this example, we output the number 0 through 9 to the console, then exit the while block, and then output a new row to the console.

Similar to the "while" loop is the "do" loop statement.

2. Listing 4-2. Do Loop: Do Loop.cs

Using System;
Class Doloop {
public static void Main () {
String MyChoice;
do {
Print A Menu
Console.WriteLine ("My Address book\n");
Console.WriteLine ("A-add New address");
Console.WriteLine ("D-delete address");
Console.WriteLine ("M-modify address");
Console.WriteLine ("V-view Addresses");
Console.WriteLine ("q-quit\n");
Console.WriteLine ("Choice (A,d,m,v,or Q):");

Retrieve the user ' s choice
MyChoice = Console.ReadLine ();
Make a decision based on the user ' s choice
Switch (mychoice) {
Case "A":
Case "a":
Console.WriteLine ("You wish to add");
Break
Case "D":
Case "D":
Console.WriteLine ("You wish to delete");
Break
Case "M":
Case "M":
Console.WriteLine ("You wish to modify");
Break
Case "V":
Case "V":
Console.WriteLine ("You are wish to view the address list.");
Break
Case "Q":
Case "Q":
Console.WriteLine ("Bye.");
Break
Default
Console.WriteLine ("{0} is not a valid choice", mychoice);
}

Pause to allow the user to the results
Console.Write ("Press any key to continue ...");
Console.ReadLine ();
Console.WriteLine ();
while (MyChoice!= "q" && mychoice!= "Q"); Keep going until the user wants to quit
}
}

Description

1. Listing 4-2 shows an example of a "do" loop. The format of the Do loop is: do {< statement >} while (< Boolean expression >), where the statement can be any legitimate C # statement, and the Boolean expression is either True or false, as in previous rules.

2. If you intend to output the information in Listing 4-2 or the menu, and then read the user's input, use the loop in the "Do" format instead of the "while" loop statement. Because in this case, the value of the Boolean expression is computed at the end of the loop, the "do" loop guarantees that the statement in the loop body executes at least once. This corresponds to the "while" loop, at the outset, evaluates the value of the Boolean expression, and the "while" loop does not guarantee that the statements in the loop body can be executed at least once.

3. Let's take a look at the content in Listing 4-2.

In the main () method, we defined the variable "MyChoice" as a string type. Then, output some information to the console, that is, to output a menu that allows the user to choose. We have to get the user input, the value returned by the Console.ReadLine () method, which is stored in the MyChoice variable. We have to get the user input before we deal with it. One effective way to do this is to use the "switch" statement. Note: To get the same functionality, we matched both lowercase letters and uppercase letters. Another point: We used the "default:" Case, which is a good programming style.

3. Listing 4-3. For loop: for Loop.cs

Using System;
Class Forloop {
public static void Main () {
for (int i=0 i < i++) {
if (i = = 10)
Break
if (i% 2 = 0)
Continue
Console.Write ("{0}", i);
}
Console.WriteLine ();
}
}

Description

1. Listing 4-3 illustrates the use of the "for" loop.

The FOR Loop statement comes in handy when you know exactly how many times a loop is being made. This procedure is the same as the run result of the "while" loop program in Listing 4-1. In the "for" loop, the contents of the brackets are composed of three semicolon-separated sections: "(< initialization table >; < Boolean expression >; <post-loop action table >)"

2. The initialization table is a comma-separated expression that is evaluated only once for the entire period of a "for" loop. The calculation is done at the beginning and before the execution of the loop statement. As you can see in listing 4-3, the initialization table is typically initialized with an integer variable that acts as a counter.

3. Once initialized, the "for" Loop enters the second part: The calculation of the Boolean expression. Boolean expressions here can be complex to write, but the result can only be true or false. Boolean expressions are typically used to validate the state of a counter variable.

4. Once the value of the Boolean expression is true, the statement in the "for" loop braces is executed. Typically, these statements start at the left Curly brace and continue to the closing brace without interruption. But in listing 4-3, with a few exceptions, several "if" statements change the process of the program.

The first "If" statement checks whether "I" is equal to 10, where the "break" statement is used, where you can jump out of the loop and move to the first statement following the "for" block.

The second "If" statement uses the remainder operator to see if "I" is divisible by 2 and executes the "continue" statement if the remainder equals 0. Control will skip the remaining statements in the loop body and move to the next round of the new loop. You need to properly organize the statements in the block and execute the corresponding statements once the conditions are met.

5. Once the program process encounters continue statements, or the closing parenthesis at the end of the block goes to the third item in the "for" loop bracket: the Post-loop action table, which is separated by commas and executes the action in the action table after the statements in the "for" block are executed. The action in the Post-loop action table in listing 4-3 is typical: Counter plus 1. Once the action table has been executed, the process moves to discriminant the Boolean expression value. The loop continues until the value of the Boolean expression is true. When the Boolean expression evaluates to False, the control process is transferred to the first statement after the "for" block.

4. Listing 4-4. The ForEach loop: ForEachloop.cs

Using System;
Class Foreachloop {
public static void Main () {
String[] names = {"Cheryl", "Joe", "Matt", "Robert"};
foreach (string person in names) {
Console.WriteLine ("{0}", person);
}
}
}

Description

1. The "foreach" loop enumerates all the elements in the collection.

The type of array used in listing 4-4 is one such collection. (in "System.Collections" can also be set by other data types.) ). In the main () method, the first thing we do is define an array of four strings names.

2. The expression in the "foreach" bracket consists of two items separated by the keyword in. The item on the right is the name of the collection, and the item on the left is the variable name that holds each element in the collection.

The loop runs as follows: Every time a loop is taken, a new element value is taken from the collection, placed in a read-only variable, and the entire expression in parentheses returns the value to True, and the statement in the "foreach" block can be executed. Once the elements in the collection have been accessed, the entire expression evaluates to False, and the control process goes to the first executable statement after the "foreach" block.

3. In the example in Listing 4-4, we used the string variable person to hold each element of the names array and use the Console.WriteLine () method to output the value of the person variable.

Summary
Until now, you have learned the use of the "while", "Do", "for" and "foreach" loop statements. Finally, you also learn how to set conditions to change the flow of statements in a loop block.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.