0
0
C++programming~5 mins

If statement in C++

Choose your learning style9 modes available
Introduction

An if statement helps your program make choices by running code only when a condition is true.

To check if a user entered the correct password before allowing access.
To decide if a number is positive or negative and print a message.
To perform an action only if a sensor detects something.
To give a discount only if the customer buys more than 5 items.
Syntax
C++
if (condition) {
    // code to run if condition is true
}

The condition is a test that is either true or false.

Curly braces { } group the code that runs when the condition is true.

Examples
This runs the message only if x is greater than zero.
C++
if (x > 0) {
    std::cout << "x is positive" << std::endl;
}
This checks if age is 18 or more before printing.
C++
if (age >= 18) {
    std::cout << "You can vote." << std::endl;
}
This runs only if score equals exactly 100.
C++
if (score == 100) {
    std::cout << "Perfect score!" << std::endl;
}
Sample Program

This program asks the user to enter a number. It then uses an if statement to check if the number is positive. If yes, it prints a message.

C++
#include <iostream>

int main() {
    int number;
    std::cout << "Enter a number: ";
    std::cin >> number;

    if (number > 0) {
        std::cout << "The number is positive." << std::endl;
    }

    return 0;
}
OutputSuccess
Important Notes

If the condition is false, the code inside the if block does not run.

You can add else or else if to handle other cases (not covered here).

Summary

An if statement runs code only when a condition is true.

Use it to make decisions in your program.

Conditions are inside parentheses and code to run is inside curly braces.