C # tutorial 3: select a control statement

Source: Internet
Author: User

This section describes how to use C # To select control statements. The third lesson will achieve the following purposes:
1. Learn how to use the "if" statement.

2. Learn how to use the "switch" statement.

3. Learn how to use the "break" statement in the "switch" statement.

4. Understand the correct usage of the "goto" statement.

In the previous lessons, all the programs you see are executed in sequence. You cannot control the input statement. All you can do is to run the program until it is terminated. This section describes how to determine based on conditions and select to enter the corresponding logical branch for execution.

The first selection statement we introduced is the "if" statement, which has three basic forms: Single Selection, if/otherwise, and multiple cases.

1. Listing 3-1. IF statement format: IfSelection. cs

Using System;
Class IfSelect {
Public static void Main (){
String myInput;
Int myInt;
Console. Write ("Please enter a number :");
MyInput = Console. ReadLine ();
MyInt = Int32.Parse (myInput );
// Single demo-and Action with brackets
If (myInt> 0 ){
Console. WriteLine ("Your number {0} is greater than zero.", myInt );
}
// Single demo-and Action without brackets
If (myInt <0)
Console. WriteLine ("Your number {0} is less than zero.", myInt );
// Either/Or demo-
If (myInt! = 0 ){
Console. WriteLine ("Your number {0} is not equal to zero.", myInt );
}
Else {
Console. WriteLine ("Your number {0} is equal to zero.", myInt );
}
// Multiple Case demo-
If (myInt <0 | myInt = 0 ){
Console. WriteLine ("Your number {0} is less than or equal to zero.", myInt );
}
Else if (myInt> 0 & myInt <= 10 ){
Console. WriteLine ("Your number {0} is between 1 and 10.", myInt );
}
Else if (myInt> 10 & myInt <= 20 ){
Console. WriteLine ("Your number {0} is between 11 and 20.", myInt );
}
Else if (myInt> 20 & myInt <= 30 ){
Console. WriteLine ("Your number {0} is between 21 and 30.", myInt );
}
Else {
Console. WriteLine ("Your number {0} is greater than 30.", myInt );
}
}
}

Description

1. All the formats of the IF statement in listing 3-1 use the same input variable "myInt ".

This is another way to obtain interactive content from users. First, we output a line of information: "Please enter a number:" to the console. "Console. the ReadLine () statement causes the program to wait for input from the user. Once the user inputs a number and presses the Enter key, the number is returned as a string to the "myInput" variable, because we need an integer, we need to convert the variable "myInput" to an integer. Run "Int32.Parse (myInput. (Int32 and other data types will be introduced in Later courses .) The conversion result is put in the "myInt" variable, which is an integer type.

 

2. With the required data type, we can use the "if" statement to determine the condition.

For the first form of IF statement, the format is: if (boolean expression) {statements }. This statement must start with the keyword "if. Then, it is a Boolean expression in parentheses. This Boolean expression must calculate a value of true or false. In this example, we check the user input to see if the input value is greater than 0. If the expression returns true, execute the statement in braces. (The statement section between braces is called "block ".) The block contains one or more statements. If the Boolean expression value is false, we ignore the statements in the block and directly execute the statements following the block.

3. Except for the absence of blocks, the format of the second "if" statement is very similar to that of the first statement.

Therefore, if the Boolean expression is true, the first statement after the Boolean expression is executed. When the value of a Boolean expression is false, the first statement after the Boolean expression is ignored and the program statement after the Boolean expression is executed directly. If you only have one statement to execute, use the "if" statement in this format. If you want to execute two or more statements when the Boolean expression value is true, you must put them in the block. My personal suggestion is: no matter how many statements need to be executed, You need to develop the habit of putting the if statement into the block. This avoids the following error: after a statement is added, we forgot to add a pair of parentheses.

4. Most of the time, you need to make the following choices: Do one thing when the conditions are met, or do another thing.

In listing 3-1, the program demonstrates the use of this if statement format. When the Boolean expression is true, the statement following "if" is executed immediately. When the Boolean expression is false, the statement following the "else" keyword is executed.

5. when you want to calculate multiple boolean expressions, you can use the if/else format. The above example demonstrates this format, starting with the keyword "if, once the Boolean expression is true, the block following the if statement is executed. However, multiple conditions can be determined after the combined keyword "else if. The "else if" statement is followed by a Boolean expression. Once the value of this Boolean expression is true, the subsequent block is executed. This situation can continue until all cases have been computed, but the entire "if/else if" sequence must end with "else. When the values of all boolean expressions after "if" or "else if" are false, the block following the keyword "else" is executed. For statements in the if/else format, only one part of the statements is executed at a time.

6. In the preceding example, the Boolean expression (myInt <0 | myInt = 0) contains the condition OR (|) operator.

For general OR (|) operators and condition OR (|) operators, the value of the entire Boolean expression is true as long as one of the subexpressions on both sides of the operator is true. The difference between the two operators is that regular OR operators (|) Calculate the expressions on both sides of the operator (|) each time. The condition operator OR (|) calculates the value of the second subexpression only when the value of the first subexpression is false.

7. The Boolean expression (myInt> 0 & myInt <= 10) contains the conditional operator AND.

For general AND (&) operators AND condition AND (&) operators, the value of the entire Boolean expression is true only when the values of the subexpressions on both sides of the operator are true. The difference between the two operators is that the regular AND (&) operator calculates the values of the subexpressions on both sides of the operator each time, but for the conditional AND operator, the value of the second expression is calculated only when the value of the first subexpression is true. Conditional operators (& and |) are generally called Operation-optimized operators, because they sometimes do not need to calculate the value of the entire expression. In this way, you can ignore unnecessary calculation of logical expressions and generate valid code.

Similar to the "if" statement in the if/else format, the "switch" statement is used as follows:

2. Listing 3-2. Branch selection statement: SwitchSelection. cs

Using System;
Class SwitchSelect {
Public static void Main (){
String myInput;
Int myInt;

Begin:
Console. Write ("Please enter a number between 1 and 3 :");
MyInput = Console. ReadLine ();
MyInt = Int32.Parse (myInput );
// Switch with integer type
Switch (myInt ){
Case 1:
Console. WriteLine ("Your number is {0}.", myInt );
Break;
Case 2:
Console. WriteLine ("Your number is {0}.", myInt );
Break;
Case 3:
Console. WriteLine ("Your number is {0}.", myInt );
Break;
Default:
Console. WriteLine ("Your number {0} is not between 1 and 3.", myInt );
}

Decide:
Console. Write ("Type \" continue \ "to go on or \" quit \ "to stop :");
MyInput = Console. ReadLine ();
// Switch with string type
Switch (myInput ){
Case "continue ":
Goto begin;
Case "quit ":
Console. WriteLine ("Bye .");
Break;
Default:
Console. WriteLine ("Your input {0} is incorrect.", myInput );
Goto decide;
}
}
}

Description

1. Listing 3-2 demonstrates the use of the switch statement for multiple branch selection.

The keyword "switch" is followed by the switch expression. The Switch expression must be of the following types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or enum. (The enum type will be introduced in Later courses ). In the first "switch" statement in listing 3-2, the switch expression calculates integer data.

2. the switch expression is followed by a switch block. When the value of the Switch expression matches the value of the constant expression after a case, the statement following this case is executed, until you encounter a "break" or "goto" statement. Each branch uses the keyword "case" as the label, followed by a constant expression, followed by a semicolon (:). In this example, we have "case 1:", "case 2:" and "case 3 :".

3. You can add a "default" branch to the selection of all branches.

If no constant expression is matched, go to the default branch and run the seven-pound statement of the branch. Although the default label is optional, we recommend that you add this branch. This will help to deal with unexpected events, so that your program can capture and handle unforeseen events, thus making the program more reliable.

4. Each "case" label must end with a "break" statement.

The "break" statement causes the program to exit the switch statement and start executing a statement after the switch block. For the "default" label, the "break" statement is optional because the running result is the same if there is a "break" Statement and no "break" statement. If you place a "goto" statement in the switch block, the situation will be different.

5. The second "switch" statement in listing 3-2 demonstrates the usage of the "goto" statement.

The "goto" Statement allows the program to jump to the label next to the keyword "goto" for execution. During program execution, if you enter "continue", the switch statement matches the constant expression in case "continue" and runs the "goto begin:" statement. The program will leave the "switch" Statement and start to execute the first statement after the label "begin. This is an effective loop that allows you to repeatedly execute the same piece of code. Once the user enters the string "quit", the loop ends. In this case, the "quit" branch is entered. This branch outputs "Bye." To the console, jumps out of the switch statement, and ends the program.

Once the input string is neither "continue" nor "quit", it will enter the "default:" branch. Therefore, an error message is output to the console, and then the "goto decide:" command is executed. This causes the program to jump to the first statement after the "decide:" label. After the statement is executed, it will ask whether the user is willing to continue or quit ). This is an effective loop.

Obviously, the "goto" statement is powerful. In controlled cases, the "goto" statement is very useful. However, it must be noted that if "goto" is abused, debugging and maintenance of the program will become very difficult. Imagine that if the program can see the goto statement everywhere, the process will become hard to read and understand. In the next lesson, we will introduce a better way to create a circular statement in a program.

Summary
Now you know how to use the format of the "if" Statement and how to use the "switch" statement. You have also learned that the "break" statement can be introduced from the "switch" statement. Finally, you learned how to use the "goto" statement to jump to another part of the program.

Related Article

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.