C++ Control Flow (if, switch) Tutorial

Control flow statements like if and switch allow you to execute different code paths based on conditions in your program.

1. The if Statement

Use the if statement to execute code conditionally:


#include <iostream>
using namespace std;

int main() {
    int number = 10;

    if (number > 5) {
        cout << "Number is greater than 5." << endl;
    } else {
        cout << "Number is 5 or less." << endl;
    }
    return 0;
}
                

In this example, the program checks if number is greater than 5 and outputs the corresponding message.

2. The switch Statement

The switch statement executes code blocks based on specific case values:


#include <iostream>
using namespace std;

int main() {
    int choice = 2;

    switch (choice) {
        case 1:
            cout << "You selected option 1." << endl;
            break;
        case 2:
            cout << "You selected option 2." << endl;
            break;
        default:
            cout << "Invalid selection." << endl;
    }
    return 0;
}
                

In this example, the program executes code based on the value of choice.

3. Nested and Combined Statements

You can combine and nest if and switch statements for more complex conditions:


if (condition1) {
    if (condition2) {
        // Nested if
    } else {
        // Else block
    }
}

switch (variable) {
    case 1:
        if (condition3) {
            // Combined with if
        }
        break;
}
                

Be careful to maintain readability when nesting and combining statements.

4. Best Practices

  • Use if for general conditions and switch for fixed values.
  • Always include a default case in a switch for unexpected values.
  • Maintain proper indentation for readability.

5. Next Steps

Explore loops and functions to add more functionality to your C++ programs!

0 Interaction
875 Views
Views
28 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home