Control Statements in C++

Control Statements in C++

Conditional Statements

if statement

The if statement checks a condition and executes a block of code only if the condition evaluates to true.

if (condition) {
    // code to be executed if condition is true
}

if-else statement

The if-else statement provides an alternative code block to execute if the condition is false.

if (condition) {
    // code to be executed if condition is true
} else {
    // code to be executed if condition is false
}

else-if ladder

The else-if ladder helps to check multiple conditions sequentially.

if (condition1) {
    // code to be executed if condition1 is true
} else if (condition2) {
    // code to be executed if condition2 is true
} else {
    // code to be executed if none of the conditions is true
}

switch statement

The switch statement allows a variable to be tested for equality against a list of values.

switch (expression) {
    case constant1:
        // code to be executed if expression equals constant1
        break;
    case constant2:
        // code to be executed if expression equals constant2
        break;
    // more cases...
    default:
        // code to be executed if no case matches
}

Loop Statements

for loop

The for loop is used when the number of iterations is known beforehand.

for (initialization; condition; update) {
    // code to be executed
}

while loop

The while loop repeatedly executes a block of code as long as the condition is true.

while (condition) {
    // code to be executed
}

do-while loop

The do-while loop executes the code block at least once before checking the condition.

do {
    // code to be executed
} while (condition);

Jump Statements

break statement

The break statement is used to exit a loop or switch statement prematurely.

// used to exit a loop or switch statement prematurely
break;

continue statement

The continue statement skips the rest of the code inside the loop for the current iteration and proceeds with the next iteration.

// skips the rest of the code inside the loop for the current iteration and proceeds with the next iteration
continue;

goto statement

The goto statement provides an unconditional jump to a labelled statement.

// jumps to the labelled statement
goto label;
label: // labelled statement