What is if-else Statement in C++?
An if-else statement allows us to handle both possibilities:
- If the condition is true, run the if block
- Else, run the else block
It is used when we want to choose between two paths. It helps the program decide what to do in different situations.
Syntax of if-else Statement:
if (condition) {
// code if condition is true
}
else {
// code if condition is false
}
How if-else Statement Works
- First, the condition is evaluated inside the if statement.
- If it is true, the if block executes.
- If it is false, the else block executes.
Example
#include <iostream>
using namespace std;
int main() {
int number = -5;
if (number >= 0) {
cout << "Positive number";
} else {
cout << "Negative number";
}
return 0;
}
Output:
Negative number
Explanation:
- The condition number >= 0 is checked.
- Since -5 is not greater than or equal to 0, the condition is false.
- So, the else block executes.
Real-Life Example
- If marks are greater than or equal to 40 → Pass
- Else → Fail
Summary:
- if-else is used for two-way decision making.
- Only one block executes at a time.
- It executes one block when condition is true and another when false.
- Curly braces { } define blocks of code.