Programs often need to choose: if the marks are above 40, print Pass, otherwise print Fail. C gives you if, else, else if and switch for this.
The if statement#
if (condition) {
// runs only when the condition is true (non-zero)
}
Heat alert! Drink water. Have a good day.
if-else#
Result: Fail
Change the input to 72 and run again.
The else-if ladder#
When there are more than two choices, chain them. C checks the conditions top to bottom and runs only the first block whose condition is true.
Units: 250, Bill: Rs 1100.00
else-if ladder में ऊपर से नीचे conditions check होती हैं। जैसे ही कोई एक condition सच मिलती है, उसका block चलता है और बाकी सब छोड़ दी जाती हैं। इसलिए conditions का क्रम (order) सही रखना ज़रूरी है - बड़ी range पहले या छोटी पहले, सोच कर लिखें।
Nested if#
An if inside another if:
Largest: 61
Without braces, an else attaches to the nearest if (the "dangling else" problem). Always use { } for nested ifs - it costs nothing and prevents bugs.
The switch statement#
switch compares one integer (or char) value against fixed case labels. It is cleaner than a long else-if ladder when you check for exact values.
switch (expression) {
case value1: statements; break;
case value2: statements; break;
default: statements; // when no case matches
}
135.00
Fall-through: grouping cases#
If a case has no break, execution continues into the next case. Sometimes that is exactly what you want:
e is a vowel
if-else vs switch#
Use if-else when... |
Use switch when... |
|---|---|
you test ranges (marks >= 60) |
you test exact values (case 1, case 'a') |
| conditions involve floats or several variables | one integer/char variable is checked |
conditions are complex (&&, ||) |
there are many fixed options (menus) |
Summary#
if (cond)runs a block whencondis non-zero;elsehandles the opposite.- An else-if ladder runs only the first true branch.
switchmatches exact integer/char values; rememberbreak, and usedefault.- Always use braces with nested ifs.