c-plus-plus
  1. c-plus-plus-if-else

C++ Control Statement if-else

Syntax

The if-else control statement in C++ has the following syntax:

if (condition) {
    // Code to execute if condition is true
} else {
    // Code to execute if condition is false
}

Example

#include <iostream>
using namespace std;

int main() {
    int num = 10;

    if (num > 5) {
        cout << "The number is greater than 5." << endl;
    } else {
        cout << "The number is less than or equal to 5." << endl;
    }

    return 0;
}

Output

The number is greater than 5.

Explanation

The if-else control statement allows us to execute different sets of code depending on the value of a certain condition. In this example, we use the condition num > 5 to determine which code block to execute.

If num is greater than 5, the first code block is executed and the message "The number is greater than 5." is printed. If num is less than or equal to 5, the second code block is executed and the message "The number is less than or equal to 5." is printed.

Use

The if-else control statement is commonly used in C++ programs to make decisions based on certain conditions. It allows the program to execute different sets of code depending on the value of the condition.

Important Points

  • The if-else control statement requires a condition to be evaluated.
  • If the condition is true, the code block associated with the if statement is executed.
  • If the condition is false, the code block associated with the else statement is executed (if present).
  • The else statement is optional, and can be omitted if no code block needs to be executed when the condition is false.

Summary

The if-else control statement in C++ is used to execute different sets of code based on a certain condition. It requires a condition to be evaluated, and executes the code block associated with the if statement if the condition is true. If the condition is false, it executes the code block associated with the else statement (if present).

Published on: