Hello, C ++ (19) "Teacher, have I passed this level 4 test ?" -- 4.2 condition selection statement, Level 4 exam 4.2

Source: Internet
Author: User

Hello, C ++ (19) "Teacher, have I passed this level 4 test ?" -- 4.2 condition selection statement, Level 4 exam 4.2
4.2 condition selection statement

"Teacher, have I passed this level 4 test ?"

How can the teacher answer this question? Yes, he will choose different answers based on different conditions:

If the examination score is greater than or equal to 60, the answer is: "Congratulations, you have passed this test ";

Otherwise, you will answer "sorry, you did not pass this test ".

This is the condition selection in the real world-making different actions based on different conditions. In C ++, how can we express this conditional selection?

4.2.1 if statement: if ...... Just ......

In the real world, we always use ......, Just ......" C ++ also learns from us and provides if (if) keywords to form a Condition Selection structure to express conditions in the real world, the syntax format is as follows:

If (condition expression) {Statement 1 ;}else {Statement 2 ;}

C ++ calculates the value of the conditional expression when executing the if condition selection statement, and then executes different code based on the value. If the value of the conditional expression is true, Statement 1 is executed directly. Otherwise, Statement 2 is executed in the else branch. By using conditional selection statements, you can change the path of program execution based on different values of conditional expressions. Different functions can be implemented in statements 1 and 2, to achieve the goal of "performing different actions according to different conditions. The execution process of the if statement is 4-1.

Now, you can use the if statement to solve the problem that the above four-level test has passed:

// Set the test score to int nScore = 0; cout <"Enter the test score:"; // enter the test score cin> nScore; // calculate the condition expression to determine whether the score meets the condition (greater than or equal to 60) // If the nScore value is greater than or equal to 60, the condition expression value is true, // directly go to the if branch for execution, and output the prompt if (nScore> = 85) {// execute the cout action that meets the conditions <"congratulations, you passed this test. "<endl;} else // if the condition is not met, the value of the conditional expression is false, then go to the else branch and execute {// execute the cout action that does not meet the condition <"sorry, you did not pass this test" <endl ;}

Figure 4-1 execution process of the conditional selection Structure

Here, let the user enter the test score, and then compare it with a standard value in the conditional expression of the if statement, that is, to determine whether the test score meets the criteria. If the score is greater than or equal to 60, the value of the conditional expression is true, which means that the program will go to the if branch for execution and output the prompt language for passing the test. Otherwise, if the test score is less than 60, the condition cannot be met, and the value of the condition expression is false, the program will go to the else branch for execution, and the prompt that the test failed will be output. In this way, the program performs different actions based on different conditions (nScore is greater than or equal to 60) (different prompts are output ).

Although the form of the if statement is simple, there are several points to note in its use.

1. if not necessary, the else branch in the if statement can be omitted

Most of the time, we only care about the situation when the condition is true, and only process the condition that meets the condition, then we can omit the else branch, only the if clause is retained to determine the condition expression and the Statement 1 after the condition is met. For example, we only give a prompt to the person who passes the test. if the person does not pass the test, we ignore the prompt and use the if statement to express it as follows:

// If (nScore> = 60) {cout <"Congratulations, you passed this test ";}

2. if statements can be nested to express multi-level conditional judgment

In an if statement, another if statement can be nested, indicating that further conditional judgment is performed under a certain precondition to express multi-level conditional judgment. For example, to compare the size relationship between the numbers v1 and v2, we need to first determine whether the two are equal. If the two are not equal, we need to continue to judge the size relationship between the two, the nested if statement is used to express it as follows:

Cout <"enter two integers:" <endl; int v1, v2; // obtain the user-entered number cin> v1> v2; if (v1! = V2) // determine whether v1 and v2 are equal. if not, continue to judge the size {// Level 2 if statement // if not, determine whether v1 is greater than v2 if (v1> v2) // greater than {cout <"v1> v2" <endl ;} else // less than {cout <"v1 <v2" <endl ;}} else // v1 and v2 are equal to {cout <"v1 = v2" <endl ;}

3. if statements can be tied together

If there are multiple conditions at the same level, you can use the parallel condition selection statement. The syntax format is as follows:

If (condition expression 1) {Statement 1;} else if (condition expression 2) {Statement 2 ;}//... Else if (condition expression n) {statement n;} else {statement n + 1 ;}

During execution, the value of condition expression 1 is calculated first. If the value is true, Statement 1 is executed in its branch, and the execution of the entire parallel condition selection statement is ended; if its value is false, the value of condition expression 2 will be calculated downward. Similarly, if its value is true, it will go to its branch to execute Statement 2 and end the entire statement, if its value is false, the same calculation process is continued. Until the end, if all the condition branches cannot be met, the final else branch is executed and the entire statement is ended. For example, we compared the sizes of v1 and v2 with the nested if statement in the previous section. In fact, there are three parallel conditions: greater than, less than, or equal. Therefore, you can also use the parallel condition structure to achieve the following:

If (v1> v2) // first determine whether v1 is greater than v2 {cout <"v1> v2" <endl;} else if (v1 <v2) // if the first condition is not met, determine whether v1 is smaller than v2 {cout <"v1 <v2" <endl;} else // If v1 is neither greater than v2, or smaller than v2, it must be equal to v2 {cout <"v1 = v2" <endl ;}

Note that when executing a parallel condition statement, it calculates the parallel expression sequentially until a condition expression is true, then go to its branch to execute and end the entire statement. Therefore, we always place the judgment that meets the conditions with a high probability in the front. We hope that the if statement will encounter a branch that meets the condition at the beginning, to avoid useless computation on conditions that are not easily met.

Note that only one of the branches of the parallel condition selection statement is executed. If multiple conditional expressions are true, only the branch with the first condition expression true is executed from top to bottom. For example:

Int nScore = 91; if (nScore> = 60) // The first condition expression is true. Enter the execution and end the entire statement {cout <"congratulations, you passed this test "<endl;} // because the first branch has executed and ended the entire statement //, even if the second condition expression is true, but it won't get execution else if (nScore> = 85) {cout <"Amazing, your score is excellent" <endl ;}

Therefore, when using the parallel condition selection statement, we should avoid repeated coverage of the condition range. Do not set multiple condition expressions to true at the same time to avoid logical confusion in the program.

Know More: Use "? : "Condition operator to express condition judgment and simplify code

Conditional operators allow an expression to have different values based on different conditions. It is the only ternary operator in C ++. Its Syntax format is as follows:

Conditional expression? Expression 1: expression 2

Similar to the condition statement, during execution, it calculates the value of the conditional expression. If the value is true, the value of expression 1 is calculated, and use it as the final result value of the entire expression. Otherwise, the value of expression 2 is calculated, which is also the final result value of the entire expression.

By using conditional operators, we can easily implement some simple functions of Condition Selection (the process of processing conditions must be both true and false, and the process is relatively simple, to simplify the code. For example, to select a larger one from two numbers, use the if Condition Statement to compare the size can be implemented as follows:

Int a, B; // enter a, B... Int m = 0; if (a> B) {m = a;} else {m = B ;}

If the conditional operator is used, the preceding condition is selected using a statement:

Int a, B; // enter a, B... Int m = (a> B )? A: B;

In the execution of "(a> B )? When a: B is used, the value of "(a> B)" is calculated first. If the value of a is large, that is, the value of the conditional expression is true, the second operand a is used as the value of the entire expression, and then assigned to m. In this way, m becomes the larger of the two numbers. In turn, if the value of B is relatively large, the value of the conditional expression is false, and B is used as the value of the entire expression, and then assigned to m, at this time, m is still the larger of the two numbers. It can be seen that a short statement has implemented the function that the entire if Condition Statement was required to implement. Simplified code is the main function of conditional operators.

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.