Hello, C + + (19) "Teacher, did I pass the level four exam?" The--4.2 conditional selection statement

Source: Internet
Author: User


4.2 Item Selection Statements


"Teacher, did I pass the level four exam?" ”



If the teacher is asked this question, how will he answer? Yes, he will choose different answers according to different conditions:



If the test result is greater than or equal to 60, then answer: "Congratulations, you passed the exam";



Otherwise, answer, "I'm sorry you didn't pass the exam."



This is the conditional choice in the real world-making different moves based on different conditions. So, in C + + programs, how do we express this conditional choice?


4.2.1 If statement: If ... Just ...


In the real world, we always use the "if ...." sentence to express the conditions of choice, C + + also learn from us, provide if (if) keyword to form a conditional selection structure, to express the real-world conditions of choice, the syntax format is as follows:

if (conditional expression)
{
    Statement 1;
}
else
{
    Statement 2;
}
When C ++ executes an if conditional selection statement, it first calculates the value of the conditional expression, and then chooses to execute different code according to the different values. If the value of the conditional expression is true, execute statement 1 directly downward; otherwise, enter the else branch to execute statement 2. By using conditional selection statements, the path of program execution can be changed according to the different values of the conditional expression, and different functions can be realized in statement 1 and statement 2, thereby achieving the purpose of "execute different actions according to different conditions". The execution process of the if statement is shown in 4-1.

Now, you can use the if statement to solve the above real problem of "level 4 has passed":

// Conditioned on test scores
int nScore = 0;
cout << "Please enter the test score:";
// Enter test score
cin >> nScore;
// Calculate the conditional expression to determine whether the test score meets the conditions (greater than or equal to 60)
// If the value of nScore is greater than or equal to 60, the condition is met, the value of the conditional expression is true,
// Then directly enter the if branch to execute, output the prompt of passing the exam
if (nScore> = 85)
{
    // Perform actions that meet the conditions
    cout << "Congratulations, you passed this exam" << endl;
}
else // If the condition is not met, the value of the conditional expression is false, then enter the else branch to execute
{
    // Perform actions that do not meet the conditions
    cout << "Unfortunately, you failed this exam" << endl;
}
                       

Figure 4-1 The execution flow of the conditional selection structure

Here, first 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, determine whether the test score meets the conditions. If the test score is greater than or equal to 60, the value of the conditional expression is true, which means that the condition is met, the program will enter the if branch to execute, and the prompt language that the test passed is output. Conversely, if the test score is less than 60 and the condition cannot be met, the value of the conditional expression is false, the program will enter the else branch to execute, and output a prompt that the test failed. This allows the program to make different actions (output different prompts) according to different conditions (nScore is greater than or equal to 60 or not).

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
Many times, we only care about the condition when the condition is true, only deal with the condition that meets the condition, then you can omit the else branch, and only retain if to judge the conditional expression and the following statement 1 matches the condition Be processed. For example, we only give hints to those who pass the exam, while those who do not pass the exam are ignored directly, expressed in if statements:

// Omit the else branch, only deal with the conditions that meet the conditions
if (nScore> = 60)
{
    cout << "Congratulations, you passed this exam";
}
2. if statements can be nested to express multiple levels of conditional judgment

One if statement can be nested in another if statement, which means that further conditional judgment is made under a certain precondition, thereby expressing multi-level conditional judgment. For example, to compare the size relationship between the input v1 and v2, we need to first determine whether they are equal, and under the premise of inequality, then continue to determine the size relationship between the two, using nested if statements Express it as:

cout << "Please enter two integers:" << endl;
int v1, v2;
// Get the number entered by the user
cin >> v1 >> v2;
if (v1! = v2) // judge whether v1 and v2 are equal, if not, continue to judge the size
{
    // Second-level if statement
    // If not equal, continue to judge 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
{
    cout << "v1 == v2" << endl;
}
3. if statement can be tied

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

if (conditional expression 1)
{
    Statement 1;
}
else if (conditional expression 2)
{
    Statement 2;
}
//…
else if (conditional expression n)
{
    Statement n;
}
else
{
    Statement n + 1;
}
During execution, the value of conditional expression 1 is calculated first. If its value is true, it enters its branch to execute statement 1, and then ends the execution of the entire parallel conditional selection statement; if its value is false, it will continue down Calculate the value of conditional expression 2. Similarly, if its value is true, enter its branch to execute statement 2, and then end the entire statement, if its value is false, continue the same calculation process downward. Until the end, if all the conditional branches cannot be satisfied, enter the last else branch to execute and end the entire statement. For example, the size comparison between v1 and v2 that we implemented earlier with nested if statements is actually three cases of juxtaposition: either greater than, less than, or equal. Therefore, the same conditional structure can also be used to achieve:

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, then judge whether v1 is less than v2
{
    cout << "v1 <v2" << endl;
}
else // If v1 is neither greater than v2 nor less than v2, then it must be equal to v2
{
    cout << "v1 == v2" << endl;
}
It should be noted here that when a parallel conditional statement is executed, the parallel conditional expressions in it are calculated one by one until the conditional expression is true, and then it enters its branch execution and ends the entire statement. Therefore, we always put the judgment of the condition with a higher chance of satisfaction in a higher position, hoping that the if statement will meet the branch that meets the condition at the beginning, so as to avoid the useless calculation of the judgment of the difficult condition.

In addition, it should be noted that the parallel conditional selection statement will only execute one of the branches. If multiple conditional expressions are true, only the first branch encountered from top to bottom will be true. . E.g:

int nScore = 91;
if (nScore> = 60) // The first conditional expression is true, enter execution and directly end the entire statement
{
    cout << "Congratulations, you passed this exam" << endl;
}
// Because the first branch has been executed and ended the entire statement
// So even if the second conditional expression is true, it will not be executed
else if (nScore> = 85)
{
    cout << "Great, your grades are excellent" << endl;
}
Therefore, when using parallel conditional selection statements, you should avoid overlapping overlapping condition ranges, and do not allow multiple conditional expressions to be true at the same time, so as not to cause confusion in the program logic.

Know more: Use "?:" Conditional operators to express conditional judgments, simplify code

The so-called conditional operator, it can make an expression have different values according to different conditions. It is the only ternary operator in C ++, and its syntax is as follows:

Conditional expression? Expression 1: Expression 2
Similar to the conditional statement, during execution, it will first calculate the value of the conditional expression, if its value is true, it will then calculate the value of expression 1, and use it as the final result value of the entire expression. Otherwise, the value of expression 2 will be calculated, which is also used as the final result value of the entire expression.

Using conditional operators, we can easily implement some simpler (to deal with both the conditions of establishment and non-establishment, and the processing process is relatively simple) condition selection function, so as to simplify the code. For example, we want to select the larger one of the two numbers, and use the if conditional statement to compare the size, which can be implemented as:

int a, b;
// Enter a, b ...
int m = 0;
if (a> b)
{
    m = a;
}
else
{
    m = b;
}
If the conditional operator is used, the above conditional selection is realized in one statement:

int a, b;
// Enter a, b ...
int m = (a> b)? a: b;
When executing "(a> b)? A: b", the value of "(a> b)" will also be calculated first. If the value of a is relatively large, that is, the value of the conditional expression is true, it will be 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. Conversely, if the value of b is relatively large, the value of the conditional expression is false, the third operand b is used as the value of the entire expression, and finally assigned to m, at this time m is still the comparison between the two numbers The big one. It can be seen that a short sentence realizes the function that only needs the entire if conditional sentence. Simplifying code is the most important role of conditional operators.

Hello, C ++ (19) "Teacher, have I passed the Level 4 exam this time?"-4.2 Conditional selection statement

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.