If...Else
C++ If...Else (Conditional Statements)
Definition: Conditional statements are used to perform different actions based on different conditions. They allow a program to make decisions at runtime—executing specific blocks of code only when certain criteria are met.
Why: The if...else structure is a core beginner C++ module because it introduces the concept of "control flow." Without conditions, a program would simply run every line of code from top to bottom. Conditions allow the program to branch out, creating interactive and "intelligent" behavior.
Basic Syntax
The if keyword is followed by a condition in parentheses. If the condition evaluates to true, the code inside the first set of curly braces executes. If it is false, the code inside the else block runs instead.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example: Pass/Fail Logic
In this example, the program checks a student's marks to determine if they have passed or failed based on a threshold of 35:
#include <iostream> using namespace std; int main() { int marks = 75; if (marks >= 35) { cout << "Pass"; } else { cout << "Fail"; } return 0; }
The "Else If" Ladder
When you have more than two possible outcomes, you can use the else if statement to specify a new condition if the first condition is false.
| Statement | Role |
|---|---|
if |
The starting point. Checks the first condition. |
else if |
Checks a secondary condition only if the previous conditions were false. You can have many of these. |
else |
The "catch-all" block. Executes if none of the above conditions were true. |
Key Notes
- Comparison Operators: Conditions usually use comparison operators like
==(equal to),!=(not equal),>,<,>=, and<=. - Non-Zero is True: In C++, any non-zero integer is treated as
true, while0is treated asfalse. This meansif (5)will always execute its block. - Shorthand If (Ternary Operator): For very simple if-else logic, you can use a one-liner called the ternary operator:
variable = (condition) ? expressionTrue : expressionFalse;. - Braces Requirement: If your
iforelseblock contains only one line of code, the curly braces are technically optional. However, it is a professional best practice to always use them to prevent logic errors when adding more lines later.