The if Statement
The if statement is used to make decisions in a program — it tells the program to execute certain code only if a specific condition is true.
Basic Syntax
if (condition)
statement;conditionis an expression that is evaluated to eithertrueorfalse.- If the condition is true, the statement is executed.
- If the condition is false, the statement is ignored, and the program continues after the
ifblock.
Example
if (x == 100)
cout << "x is 100";If x is exactly 100, the message "x is 100" is printed. Otherwise, nothing happens and the program simply moves on.
Multiple Statements (Compound Block)
If you want to execute more than one statement when the condition is true, group them inside curly braces {} to form a block:
if (x == 100)
{
cout << "x is ";
cout << x;
}This block is treated as one single statement. Indentation and line breaks don’t affect how the program runs, so this is equivalent to:
if (x == 100) { cout << "x is "; cout << x; }Using else
You can add an else clause to specify what happens when the condition is false:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";If the condition is true, the first statement runs. If it’s false, the statement after else runs instead.
else if Chains
You can chain multiple conditions using else if to handle multiple cases:
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";This structure allows your program to decide among several alternatives:
- If
xis greater than zero → prints “x is positive” - If
xis less than zero → prints “x is negative” - Otherwise → prints “x is 0”