0
0
C++programming~5 mins

If–else statement in C++

Choose your learning style9 modes available
Introduction

An if-else statement helps your program make choices. It runs different code depending on a condition.

Deciding if a user is old enough to access a website.
Checking if a number is positive or negative.
Choosing what message to show based on a score.
Turning on a light if it is dark outside.
Syntax
C++
if (condition) {
    // code to run if condition is true
} else {
    // code to run if condition is false
}
The condition is a test that is either true or false.
Only one block runs: either the if part or the else part.
Examples
This checks if number is greater than zero.
C++
int number = 10;
if (number > 0) {
    // number is positive
} else {
    // number is zero or negative
}
This decides what to do based on the weather.
C++
bool isRaining = false;
if (isRaining) {
    // take umbrella
} else {
    // no umbrella needed
}
Sample Program

This program asks for your age and tells you if you are an adult or a minor using an if-else statement.

C++
#include <iostream>

int main() {
    int age;
    std::cout << "Enter your age: ";
    std::cin >> age;

    if (age >= 18) {
        std::cout << "You are an adult.\n";
    } else {
        std::cout << "You are a minor.\n";
    }

    return 0;
}
OutputSuccess
Important Notes

Make sure the condition inside if uses comparison operators like ==, >, <.

Use braces { } even for one line inside if or else to avoid mistakes.

Summary

If-else lets your program choose between two paths.

The if block runs when the condition is true.

The else block runs when the condition is false.