C++ If Statement

The if statement in C++ is used to execute a block of code only if a specified condition evaluates to true. It is the most basic control structure for decision-making.

Syntax

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

Example Program

#include <iostream>
using namespace std;

int main() {

    int number;
    cout << "Enter a number: ";
    cin >> number;

    // If statement
    if (number > 0) {
        cout << "The number is positive." << endl;
    }

    return 0;
}

Output (example)

Enter a number: 10
The number is positive.

Key Points

  • The condition inside parentheses ( ) must evaluate to a boolean value (true or false).
  • If the condition is false, the code block inside the if statement is skipped.
  • Braces { } are optional for a single statement, but recommended for readability.

Next Topic

After learning if statements, you can continue to C++ If-Else Statements to handle both true and false conditions.