Control Structures

if-else Statement

85
B
Good!

switch Statement

10 + 5 = 15

Simple if Statement

#include <iostream>

int main() {
    int age = 18;
    
    if (age >= 18) {
        std::cout << "You are an adult." << std::endl;
    }
    
    return 0;
}

if-else Statement

#include <iostream>

int main() {
    int number = 7;
    
    if (number % 2 == 0) {
        std::cout << number << " is even." << std::endl;
    } else {
        std::cout << number << " is odd." << std::endl;
    }
    
    return 0;
}

if-else if-else Statement

#include <iostream>

int main() {
    int score = 85;
    
    if (score >= 90) {
        std::cout << "Grade: A" << std::endl;
    } else if (score >= 80) {
        std::cout << "Grade: B" << std::endl;
    } else if (score >= 70) {
        std::cout << "Grade: C" << std::endl;
    } else if (score >= 60) {
        std::cout << "Grade: D" << std::endl;
    } else {
        std::cout << "Grade: F" << std::endl;
    }
    
    return 0;
}

switch Statement

#include <iostream>

int main() {
    int day = 3;
    
    switch (day) {
        case 1:
            std::cout << "Monday" << std::endl;
            break;
        case 2:
            std::cout << "Tuesday" << std::endl;
            break;
        case 3:
            std::cout << "Wednesday" << std::endl;
            break;
        case 4:
            std::cout << "Thursday" << std::endl;
            break;
        case 5:
            std::cout << "Friday" << std::endl;
            break;
        case 6:
        case 7:
            std::cout << "Weekend" << std::endl;
            break;
        default:
            std::cout << "Invalid day" << std::endl;
            break;
    }
    
    return 0;
}

Ternary Operator

#include <iostream>

int main() {
    int a = 10, b = 20;
    
    // Using ternary operator
    int max = (a > b) ? a : b;
    std::cout << "Maximum: " << max << std::endl;
    
    // Another example
    int age = 16;
    std::string status = (age >= 18) ? "Adult" : "Minor";
    std::cout << "Status: " << status << std::endl;
    
    return 0;
}

Nested if Statements

#include <iostream>

int main() {
    int age = 25;
    bool hasLicense = true;
    
    if (age >= 18) {
        if (hasLicense) {
            std::cout << "You can drive!" << std::endl;
        } else {
            std::cout << "You need a license to drive." << std::endl;
        }
    } else {
        std::cout << "You are too young to drive." << std::endl;
    }
    
    return 0;
}