CodeToLive

Control Structures in C++

Control structures in C++ allow you to control the flow of your program. They include conditional statements (if-else, switch) and loops (for, while, do-while). These structures are essential for making decisions and repeating tasks in your code.

If-Else Statements

The if-else statement is used to execute a block of code based on a condition. You can also use else if to check multiple conditions.


#include <iostream>

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

Switch Statement

The switch statement is used to execute one of many code blocks based on the value of an expression. It is often used as an alternative to multiple if-else statements.


#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;
        default:
            std::cout << "Invalid day" << std::endl;
    }
    return 0;
}
      

Loops

Loops are used to execute a block of code repeatedly. C++ supports three types of loops:


#include <iostream>

int main() {
    // For Loop
    for (int i = 0; i < 5; i++) {
        std::cout << "For Loop: " << i << std::endl;
    }

    // While Loop
    int count = 0;
    while (count < 5) {
        std::cout << "While Loop: " << count << std::endl;
        count++;
    }

    // Do-While Loop
    int num = 0;
    do {
        std::cout << "Do-While Loop: " << num << std::endl;
        num++;
    } while (num < 5);

    return 0;
}
      

Nested Loops

Loops can be nested inside other loops to handle more complex scenarios, such as working with multi-dimensional arrays.


#include <iostream>

int main() {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            std::cout << "i = " << i << ", j = " << j << std::endl;
        }
    }
    return 0;
}
      

Break and Continue

The break statement is used to exit a loop or switch statement prematurely. The continue statement skips the rest of the loop body and proceeds to the next iteration.


#include <iostream>

int main() {
    // Break Example
    for (int i = 0; i < 10; i++) {
        if (i == 5) {
            break;  // Exit the loop when i is 5
        }
        std::cout << "Break Example: " << i << std::endl;
    }

    // Continue Example
    for (int i = 0; i < 10; i++) {
        if (i % 2 == 0) {
            continue;  // Skip even numbers
        }
        std::cout << "Continue Example: " << i << std::endl;
    }
    return 0;
}
      

Best Practices

Next: Functions