C++ Series 8: Selection, Loop and Steering

1. Select statement

A select statement uses conditions to determine which code a program will execute. In C++ programming, there are many types of selection statements, including if statements, switch statements, and ternary operators.

(1) ifStatement

ifThe statement is one of the most common selection statements in C++ programming. The syntax is as follows:

if (condition)
{
    
    
    statement;
}

Among them, condition is a Boolean expression, if its value is true, execute statement. If the condition is true false, the program skips the if statement and executes the subsequent code.

ifStatements can also take an optional elseclause to execute other statements if the condition is not met. Its syntax is as follows:

if (condition)
{
    
    
    statement1;
}
else
{
    
    
    statement2;
}

In this case, if the condition is true, execute statement1, otherwise execute statement2.

Applicable scene:

  • Control the execution flow of the code
  • Execute different blocks of code based on conditions

e.g

#include <iostream>

using namespace std;

int main()
{
    
    
    int num = 5;

    if (num > 0)
    {
    
    
        cout << "Number is positive." << endl;
    }
    else if (num < 0)
    {
    
    
        cout << "Number is negative." << endl;
    }
    else
    {
    
    
        cout << "Number is zero." << endl;
    }

    return 0;
}

This program will output different messages depending on the value of the variable num.

(2) switchStatement

switchA statement is another common selection statement, which selects a block of code to execute based on the value of an expression. The syntax is as follows:

switch (expression)
{
    
    
    case value1:
        statement1;
        break;

    case value2:
        statement2;
        break;

    default:
        statement3;
}

In this case, the value of the expression will be compared with the value of each case. If a case value is matched, execute the corresponding statement and jump out of the switch statement. If no value is matched, the default block is executed (optional).

Applicable scene:

  • Execute different code blocks based on different conditions
  • Optimize the structure and code style of if-else statements

e.g

#include <iostream>

using namespace std;

int main()
{
    
    
    int num = 2;

    switch (num)
    {
    
    
        case 1:
            cout << "Monday" << endl;
            break;

        case 2:
            cout << "Tuesday" << endl;
            break;

        case 3:
            cout << "Wednesday" << endl;
            break;

        default:
            cout << "Invalid day" << endl;
            break;
    }

    return 0;
}

This program will output the corresponding day of the week according to the value of the variable num.

(3) Ternary operator

The ternary operator is a simple selection statement that can be used to select two different values ​​based on a condition. The syntax is as follows:

condition ? value1 : value2;

trueThe statement will return value1 if the condition is and value2 otherwise.

Applicable scene:

  • Simple one-line conditional judgment
  • Optimize the structure and code style of if-else statements

e.g

#include <iostream>

using namespace std;

int main()
{
    
    
    int num = 3;
    string message = (num > 0) ? "Number is positive." : "Number is negative or zero.";

    cout << message << endl;

    return 0;
}

This program will output the corresponding message according to the value of the variable num.

2. Loop statement

Loop statements in C++ include for, , whileand do whileloop, which can be used to perform a series of repeated actions until a certain condition is no longer satisfied.

Each loop structure has its unique advantages and applicable scenarios, and can be adjusted according to the situation to achieve flexible loop control.

1. forCycle

forLoop is one of the most basic repetition structures in C++, the syntax is as follows:

for (init; condition; increment)
{
    
    
    // 循环体
}

Among them, init is a loop initialization expression, used to initialize the loop counter; condition is a loop condition expression, as long as its value is true, the loop will continue to execute; increment is a loop update expression, used to update the loop counter. The body of the loop is the block of code to be executed repeatedly.

forThe advantage of the loop is that it is easy to grasp, and flexible loop control can be realized by adjusting the loop initialization expression, loop condition expression, and loop update expression. However, with some complex loop controls, forloops can become unmanageable.

Applicable scene:

  • Work with data that has a fixed number of elements, such as arrays or lists
  • Executes an action that needs to be performed a specific number of times

e.g

#include <iostream>

using namespace std;

int main()
{
    
    
    int i, n;

    cout << "Enter a positive integer: ";
    cin >> n;

    for (i = 1; i <= n; i++)
    {
    
    
        cout << i * i << " ";
    }

    return 0;
}

This program takes a positive integer n and prints the square of 1 to n.

(2) whilecycle

whileA loop is a more general repeating structure with the following syntax:

while (condition)
{
    
    
    // 循环体
}

The condition here is a boolean expression, if its value is true, then continue to execute the code block in the loop body. After the body of the loop has finished executing, the condition is re-evaluated, and if it is still true, the body of the loop is executed again.

Loops are more flexible than forloopswhile

Applicable scene:

  • Perform actions that require certain conditions to be met
  • Handling dynamically sized datasets

e.g

#include <iostream>

using namespace std;

int main()
{
    
    
    int i = 0;

    while (i < 10)
    {
    
    
        cout << i << " ";
        i++;
    }

    return 0;
}

This program will print out the numbers from 0 to 9.

(3) do whilecycle

do whileLoop is another repetitive structure in C++, the syntax is as follows:

do
{
    
    
    // 循环体
} while (condition);

In whilecontrast to loops, do whileloops guarantee that the body of the loop will be executed at least once because whilethe condition is tested after the body of the loop is executed.

Applicable scene:

  • Perform an action that needs to be performed at least once
  • Handle situations where information is obtained from users or other sources

e.g

#include <iostream>

using namespace std;

int main()
{
    
    
    int i = 0;

    do 
    {
    
    
        cout << i << " ";
        i++;
    } while (i < 10);

    return 0;
}

This program will print out the numbers from 0 to 9 inclusive.

3. Go to statement

The steering statement in C++ is a statement used to change the execution order of the program. When the program encounters the steering statement, it will skip some codes or jump to the specified code location for execution.

Steering statements in C++ include gotostatement, breakstatement, continuestatement, and returnstatement. Each statement has its unique advantages and applicable scenarios, and can achieve more efficient and flexible control flow in programming.

(1) gotoStatement

gotoThe statement is one of the most basic steering statements in C++, the syntax is as follows:

goto label;
//...
label: statement;

Among them, label is the label name, which should be unique and defined in the same function, and statement is the statement to be executed.

When the program executes gotoa statement, it will jump to the label to execute the corresponding statement. Because gotostatements are so flexible, they can be used to solve certain problems, but if used incorrectly, they can also make code difficult to understand and maintain.

Applicable scene:

  • Break out of loops in nested structures
  • Implement error handling in functions

e.g

#include <iostream>

using namespace std;

int main()
{
    
    
    int i = 0;

    loop:
        cout << i << " ";
        i++;

        if (i < 10)
            goto loop;

    return 0;
}

This program will print out the numbers from 0 to 9.

(2) breakStatement

breakstatement is another statement used to divert control flow, the syntax is as follows:

while (condition)
{
    
    
    // 循环体

    if (condition)
    {
    
    
        break;
    }
}

When breaka statement is encountered, the program will immediately jump out of the statement block and execute the code following the statement.

Applicable scene:

  • break out of the loop
  • Jump out of the specified structure in a multi-level nested structure

e.g

#include <iostream>

using namespace std;

int main()
{
    
    
    int i = 0;

    while (i < 10)
    {
    
    
        cout << i << " ";
        i++;

        if (i == 5)
            break;
    }

    return 0;
}

This program will print out the numbers from 0 to 4.

(3) continueStatement

continueA statement is also a statement used to skip some code, the syntax is as follows:

while (condition)
{
    
    
    // 循环体

    if (condition)
    {
    
    
        continue;
    }

    // 其他代码
}

When continuea statement is encountered, the program skips the code following it and starts the next loop iteration.

Applicable scene:

  • skip current loop iteration
  • skip the specified structure in a multi-level nested structure

e.g

#include <iostream>

using namespace std;

int main()
{
    
    
    int i = 0;

    while (i < 10)
    {
    
    
        i++;

        if (i == 5)
            continue;

        cout << i << " ";
    }

    return 0;
}

This program will print out the numbers from 1 to 10, excluding the number 5.

(4) returnStatement

returnA statement is also a switch statement, which can be used to return from a function and provide an optional return value. The syntax is as follows:

return expression;

where expression is the value to return.

Applicable scene:

  • return from function
  • return a value to the calling function

e.g

#include <iostream>

using namespace std;

int square(int x)
{
    
    
    return x * x;
}

int main()
{
    
    
    int result = square(5);
    cout << result << endl;

    return 0;
}

This program will calculate and print out the value 25.

4. Summary

Naive record of learning C++ language 20 years agoinsert image description here

Guess you like

Origin blog.csdn.net/apr15/article/details/130653463