C # Tutorial Lesson Three: Select a control statement

Source: Internet
Author: User
Tags exit constant continue expression goto integer readline
Tutorials | control | Statements This section describes how to use C # to select a control statement, and the third lesson will achieve the following objectives:
1. Learn the use of "if" statements.

2. Learn the use of 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 first few lessons, the programs you see are executed sequentially. You can't control the input statement, all you can do is follow the program until it terminates. In this lesson, you will introduce criteria based judgment and choose to go into the appropriate logical branches to perform.

The first selection statement we introduce is the "if" statement, which has three basic forms: single selection, if/otherwise, and multiple case selection.

1. Listing 3-1. Format of If statement: 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 Decision and Action with brackets
if (MyInt > 0) {
Console.WriteLine ("Your number {0} is greater than zero.", myInt);
}
Single Decision and Action without brackets
if (MyInt < 0)
Console.WriteLine ("Your number {0} is less than zero.", myInt);
either/or Decision
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 Decision
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", myInt);
}
else if (myInt > && myInt <= 20) {
Console.WriteLine ("Your number {0} is between", myInt);
}
else if (myInt > && myInt <= 30) {
Console.WriteLine ("Your number {0} is between", myInt);
}
else {
Console.WriteLine ("Your number {0} is greater than", myInt);
}
}
}

Description

1. The format of the IF statement in Listing 3-1 uses the same input variable "myInt".

This is another way to get interactive content from the user. We first output one line of information: "Please enter a number:" to the console. The "Console.ReadLine ()" statement causes the program to wait for input from the user, and once the user enters a number and presses the ENTER key, the number is returned to the "myinput" variable as a string, and because we need an integer, we need to convert the variable "myinput" into integer data. Use the command "Int32.Parse (myinput)" to complete. Data types, such as Int32, are described in a later course. The result of the transformation is placed in the "myInt" variable, which is an integer type.

2. With the type of data we need, we can use the "if" statement to make conditional judgments.

For the first form of the IF statement, the format is: if (Boolean expression) {statements}. The statement must start with the keyword "if". Followed by a Boolean expression in parentheses. The Boolean expression must calculate a value of true or false. In this case, we examine the user's input to see if the input value is greater than 0, and if the expression evaluates to TRUE, executes the statement in curly braces. (We refer to the statement section between curly braces as "block.") There is one or more statements in the block. If the Boolean expression evaluates to False, we ignore the statement in the block and execute the statement immediately after the block.

3. In addition to the absence of blocks, the second "if" statement is very similar in format to the first.

Therefore, if the Boolean expression is true, the first statement after the Boolean expression is executed. When the Boolean expression evaluates to False, the first statement after the Boolean expression is ignored, and the following program statement is executed directly. If you have only one statement to execute, use the "if" statement in that format. If you're going to execute two or more statements when the Boolean expression evaluates to True, you have to put them in a block. My personal advice is to get into the habit of putting an if statement into a block, whether you need to execute a few statements, and this prevents you from making the following error: When you add a statement, you forget to add a pair of parentheses.

4. Most of the time, you need to make the following choices: Do one thing when the condition is met, otherwise do something else.

In Listing 3-1, the program demonstrates the use of this if statement format. When the Boolean expression is true, the statement immediately following the "If" is executed, and the statement following the "Else" keyword is executed when the Boolean expression is false.

5. When you want to compute multiple Boolean expressions, you can use If/else if/else this format, the example program above demonstrates this form, starting with the keyword "if", and once the Boolean expression is true, execute the block after the IF. This time, however, multiple conditions can be judged after the combination of the keyword "else if". There is also a Boolean expression following the "else if" statement, which, once the value of the Boolean expression is true, executes the block immediately following it. This situation can continue until all cases have been computed, but the entire "if/else if" sequence must end with "else". When all the Boolean expressions following the "if" or "else if" value are false, the block after the keyword "else" is executed. For statements in If/else If/else format, only one part of the statement is executed at a time.

6. In the above example, the Boolean expression (MyInt < 0 | | | myInt = 0) contains the condition or (| |) Operator.

For General or (|) Operators and Conditions or (| |) operator, the value of the entire Boolean expression is true as long as one of the subexpression on either side of the operator is true. The difference between the two operators is that the normal or operator (|) Each time the operator (|) The expressions on both sides are evaluated. While the conditional operator or (| |) The value of the second subexpression is evaluated only if the value of the first subexpression is false.

7. Boolean expressions (MyInt > 0 && myInt <= 10) contain the conditional operator and.

For the General and (&) operators and the condition and (&&) operators, the value of the entire Boolean expression is true only if the value of the subexpression on both sides of the operator is true. The difference between the two operators is that the normal and (&) operators compute the values of the subexpression on both sides of the operator each time, but for the conditional and operator, the value of the second expression is evaluated only if the value of the first subexpression is true. The conditional operators (&& and | |) are often referred to as operators of operation optimizations, because the value of the entire expression is sometimes not required to be evaluated. This allows you to ignore the calculation of unnecessary logical expressions and generate valid code.

Similar to the "if" statement in the If/else if/else format, the use of the "switch" statement is 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 illustrates the use of the multiple-branch selection statement switch.

After the keyword "switch" is the switch expression. The switch expression must be one of the following types: Sbyte,byte,short,ushort, int,uint,long,ulong,char,string, or enum type. (The type of enum will be covered in a later course). In the first "switch" statement in Listing 3-2, the switch expression evaluates to an integer type of data.

2. After the switch expression is a switch block, when the value of the switch expression matches the value of the constant expression after a case, executes the statement following it until the "break" statement or "GOTO" statement is encountered. Each branch is labeled with the keyword "case", followed by a constant expression, followed by a semicolon (:). In this example program, we have "Case 1:", "Cases 2:" and "Box 3:".

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

If there is no matching constant expression, it enters the default branch and executes the statement for that branch. Although the default label is optional, I recommend that you add the branch. This will help to handle unexpected events, allowing your program to capture and handle unforeseen events, making the program more reliable.

4. Each "case" label must be terminated with a "break" statement.

The break statement causes the program to exit the switch statement and start execution from a statement that follows the switch block. For the "default" label, the break statement is optional, because there are "break" statements and no "break" statements, and they run the same result. If you place a "goto" statement in the switch block, the situation is different.

5. The second "switch" statement in Listing 3-2 demonstrates the use of the goto statement.

The goto statement enables the program to jump to the label following the keyword "goto". During program execution, if the user has entered "continue", the switch statement matches the constant expression in case "continue" and executes the Goto BEGIN: statement. The program leaves the switch statement and begins execution of the first statement after the label "Begin:". This is an effective loop that allows you to repeat the same piece of code multiple times. Once the user has entered the string "quit", the loop will end. At this point, you will enter the case "quit" branch. The branch will output the information "Bye." To the console, then jumps out of the switch statement, and then ends the program.

Once the string entered is neither "continue" nor "quit", it goes to the "Default:" Branch. As a result, an error message will be output to the console, followed by the "Goto decide:" Command. This causes the program to skip to the first statement after the "decide:" label, which will ask the user if they want to continue (continue) or quit (exit). This is an effective loop.

Clearly, the "goto" statement is powerful and, in a controlled situation, the "goto" statement is very useful. However, it must be noted that "goto" if there is a trend of abuse, debugging and maintenance of the program will become very difficult. Imagine that the process will become difficult to read and understand if a goto statement is visible everywhere. In the next lesson, you will describe a better way to create circular statements in your programs.

Summary
Now you know how to use the various formats of the "if" statement and how to use the "switch" statement. As you can see, use the break statement to eject from the switch statement. Finally, you also 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.