In C++, the if statement is the simplest decision-making statement. It is used to execute a block of code only when a specified condition evaluates to true. If the condition evaluates to false, the statements inside the if block are skipped.
- The condition can be any expression that evaluates to a Boolean value (true or false).
- If curly braces {} are omitted, only the immediately following statement is considered part of the if block.
#include <iostream>
using namespace std;
int main() {
int i = 10;
// If statement
if (i < 15) {
cout << "10 is less than 15";
}
return 0;
}
Output
10 is less than 15
Explanation: The variable i is initialized with the value 10. Since the condition i < 15 evaluates to true, the statement inside the if block is executed. If the condition were false, the block would be skipped.
Syntax
if (condition) {
// Statements to execute if
// condition is true
}
The condition can be any valid expression that evaluates to a Boolean value. Relational and equality operators are commonly used when writing conditions.
Working of if Statement in C++
The working of an if statement is as follows:

- Control reaches the if statement.
- The condition is evaluated.
- If the condition evaluates to true, proceed to Step 4; otherwise, proceed to Step 5.
- The statements inside the if block are executed.
- Control moves to the statement immediately following the if block.
Flowchart of if in C++
The following flowchart illustrates how program control flows through an if statement based on the evaluation of its condition.

Examples
The below example demonstrate how to use if statement to change the flow of the program in C++:
Check if a Number is Even
The following program checks whether a number is even by verifying if it is divisible by 2.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n = 8;
// Condition to check for even number
if (n % 2 == 0)
cout << " Even";
return 0;
}
Output
Even
Note: If curly braces {} are omitted, only the immediately following statement is considered part of the if block.
Check if a Number is Even and Less Than 10
Multiple conditions can be checked by nesting one if statement inside another.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n = 8;
// Condition to check for even number
if (n % 2 == 0) {
// Condition to check for less than 10
if (n < 10) {
cout << "Even and less than 10";
}
}
return 0;
}
Output
Even and less than 10
Check if a Number Lies Within a Range
A range check typically requires both lower and upper bound comparisons.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n = 5;
// Check whether n is the range [0, 10]
if (n <= 10 && n >= 0) {
cout << "In range";
}
return 0;
}
Output
5 is in the range [10, 20]