C ProgrammingUnit 411 min read
Control Structures (Selection): if-else, switch, nested conditions
Unit 4 of C Programming covers decision-making in programs using if, if-else, else-if, switch-case, and nested conditions. Learn syntax, logical operators, and how to structure branching logic for real-world scenarios like loan approvals, menu-driven apps, and traffic signal control.
TAKEAWAYS:
- Understand how
if,else-if, andelseexecute based on boolean conditions. - Master the
switch-casestructure for multi-way branching and its limitations. - Learn to combine conditions using logical operators (
&&,||,!) for complex decisions. - Visualize how nested conditions work with real-world examples (e.g., bank loan eligibility).
- Avoid common pitfalls like missing
breakinswitchor redundant conditions. - Apply selection structures to solve problems like menu-driven programs or grade calculators.
1. Introduction to Selection Structures
Selection structures allow a program to execute different blocks of code based on a condition. In C, the primary selection structures are:
ifstatement: Executes a block if a condition is true.if-elsestatement: Executes one block if true, another if false.else-if(ladder): Checks multiple conditions sequentially.switch-case: Efficient for multi-way branching (e.g., menu-driven programs).
Why use selection? Without selection, programs would execute linearly, making them inflexible. For example:
- A bank approves a loan only if the applicant’s credit score > 600 and income > 50,000.
- A traffic light changes color based on sensor input.
2. if Statement
Syntax
if (condition) {
// Code to execute if condition is true
}
- The
conditionmust evaluate totrue(non-zero) orfalse(zero). - The block can have one or more statements (enclosed in
{}).
Example: Check Even/Odd
#include <stdio.h>
int main() {
int num = 7;
if (num % 2 == 0) {
printf("%d is even.", num);
}
return 0;
}
Output:
7 is not even. (No output, since condition is false)
Visualization: Flow of if
flowchart TD
A["Start"] --> B["Check condition (num % 2 == 0)?"]
B -->|"True"| C["Print 'even'"]
B -->|"False"| D["End"]
C --> DReal-World Example: Loan Approval (Nepal Bank)
- Scenario: A bank approves a loan if the applicant’s income > 50,000.
- Code:
float income = 45000; if (income > 50000) { printf("Loan approved!\n"); } - Output: No output (loan denied).
3. if-else Statement
Syntax
if (condition) {
// True block
} else {
// False block
}
- Executes the
elseblock only if the condition is false.
Example: Positive/Negative Check
int num = -3;
if (num >= 0) {
printf("%d is positive.", num);
} else {
printf("%d is negative.", num);
}
Output:
-3 is negative.
Visualization: Flow of if-else
flowchart TD
A["Start"] --> B["Check condition (num >= 0)?"]
B -->|"True"| C["Print 'positive'"]
B -->|"False"| D["Print 'negative'"]
C --> E["End"]
D --> EReal-World Example: Traffic Signal Control (NTC)
- Scenario: A traffic light turns red if no vehicles are detected for 30 seconds.
- Code:
int vehicleDetected = 0; if (vehicleDetected == 1) { printf("Keep green light.\n"); } else { printf("Turn red light.\n"); }
4. else-if (Ladder)
Syntax
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Default case
}
- Checks conditions sequentially. Only the first true condition executes.
Example: Grade Calculator
int marks = 85;
if (marks >= 90) {
printf("Grade: A");
} else if (marks >= 80) {
printf("Grade: B");
} else if (marks >= 70) {
printf("Grade: C");
} else {
printf("Grade: F");
}
Output:
Grade: B
Visualization: Flow of else-if
flowchart TD
A["Start"] --> B["marks >= 90?"]
B -->|"True"| C["Grade A"]
B -->|"False"| D["marks >= 80?"]
D -->|"True"| E["Grade B"]
D -->|"False"| F["marks >= 70?"]
F -->|"True"| G["Grade C"]
F -->|"False"| H["Grade F"]
C --> I["End"]
E --> I
G --> I
H --> IReal-World Example: Daraz Order Status
- Scenario: Daraz shows different messages based on order status:
status = 1: "Processing"status = 2: "Shipped"status = 3: "Delivered"
- Code:
int status = 2; if (status == 1) { printf("Processing\n"); } else if (status == 2) { printf("Shipped\n"); } else if (status == 3) { printf("Delivered\n"); }
Output:
Shipped
5. Nested if-else
Syntax
if (condition1) {
if (condition2) {
// Nested true block
} else {
// Nested false block
}
} else {
// Outer false block
}
- Used for complex decisions (e.g., checking multiple criteria).
Example: Bank Loan Eligibility
float income = 60000;
int creditScore = 650;
if (income > 50000) {
if (creditScore >= 600) {
printf("Loan approved!\n");
} else {
printf("Low credit score. Loan denied.\n");
}
} else {
printf("Income too low. Loan denied.\n");
}
Output:
Loan approved!
Visualization: Nested if-else Flow
flowchart TD
A["Start"] --> B["income > 50000?"]
B -->|"False"| C["Income too low"]
B -->|"True"| D["creditScore >= 600?"]
D -->|"False"| E["Low credit score"]
D -->|"True"| F["Loan approved"]
C --> G["End"]
E --> G
F --> GReal-World Example: Pathao Driver Bonus
- Scenario: Pathao gives a bonus if:
- Driver completes > 10 rides and
- Average rating > 4.5.
- Code:
int rides = 12; float rating = 4.7; if (rides > 10) { if (rating > 4.5) { printf("Bonus: $20\n"); } }
Output:
Bonus: $20
6. Logical Operators
Combine conditions using:
&&(AND): Both conditions must be true.||(OR): At least one condition must be true.!(NOT): Inverts the condition.
Example: Login System (Khalti)
char username[20] = "user123";
char password[20] = "pass123";
char inputUser[20] = "user123";
char inputPass[20] = "wrongpass";
if (strcmp(username, inputUser) == 0 && strcmp(password, inputPass) == 0) {
printf("Login successful!\n");
} else {
printf("Invalid credentials.\n");
}
Output:
Invalid credentials.
Comparison Table: Logical Operators
| Operator | Name | Example (A && B) |
Result if A=true, B=false |
|---|---|---|---|
&& |
AND | true && false | false |
| ` | ` | OR | |
! |
NOT | !true | false |
7. switch-case Statement
Syntax
switch (expression) {
case constant1:
// Code for constant1
break;
case constant2:
// Code for constant2
break;
default:
// Default case
}
- Key Points:
expressionmust be an integer, character, or enum.breakprevents "fall-through" (executing next cases unintentionally).defaultruns if no case matches.
Example: Menu-Driven Program
int choice = 2;
switch (choice) {
case 1:
printf("Option 1 selected\n");
break;
case 2:
printf("Option 2 selected\n");
break;
default:
printf("Invalid option\n");
}
Output:
Option 2 selected
Visualization: switch-case Flow
flowchart TD
A["Start"] --> B["choice = 2"]
B --> C["case 1?"]
C -->|"No"| D["case 2?"]
D -->|"Yes"| E["Option 2 selected"]
D -->|"No"| F["default"]
E --> G["End"]
F --> GReal-World Example: YouTube Video Controls
- Scenario: YouTube uses
switch-casefor playback controls:1: Play2: Pause3: Stop
- Code:
int control = 2; switch (control) { case 1: printf("Playing...\n"); break; case 2: printf("Paused.\n"); break; case 3: printf("Stopped.\n"); break; default: printf("Invalid control.\n"); }
Output:
Paused.
Common Pitfalls
- Missing
break: Causes fall-through.switch (x) { case 1: printf("One"); // No break! case 2: printf("Two"); // Executes if x=1! } - Non-integer expressions: Compile-time error.
switch (3.14) { // Error: float not allowed
8. Ternary Operator (?:)
A shorthand for simple if-else:
condition ? expr1 : expr2;
- If
conditionis true,expr1executes; else,expr2.
Example: Maximum of Two Numbers
int a = 5, b = 10;
int max = (a > b) ? a : b;
printf("Max: %d", max); // Output: 10
9. Comparison with Other Languages
| Feature | C (if-else) |
Python (if-else) |
JavaScript (switch) |
|---|---|---|---|
| Syntax | if (x > 0) |
if x > 0: |
switch(x) { case 1: } |
| Case Sensitivity | Yes (strict) | Yes | Yes |
| Fall-through | Requires break |
No fall-through | Requires break |
10. Advantages and Disadvantages
| Selection Type | Advantages | Disadvantages |
|---|---|---|
if-else |
Flexible, works with any condition. | Can become messy with many conditions. |
switch-case |
Clean for multi-way branching. | Limited to constants, no ranges. |
Nested if-else |
Handles complex logic. | Hard to read if overused. |
| Ternary Operator | Concise for simple conditions. | Not suitable for complex logic. |
In the Real World
eSewa (Nepali Digital Payment)
- Uses
if-elseto validate transactions:if (balance >= amount) { deductBalance(amount); sendMoney(receiver); } else { showError("Insufficient funds"); } - How it works: Checks if the user’s balance is sufficient before processing a payment.
- Uses
Pathao (Ride-Hailing App)
- Uses
switch-casefor driver actions:switch (driverAction) { case ACCEPT_RIDE: startNavigation(); break; case REJECT_RIDE: notifyUser(); break; default: logError(); } - How it works: Drivers select options (accept/reject), and the app responds accordingly.
- Uses
Nepal Electricity Authority (NEA) Billing
- Uses nested
if-elseto calculate bills:if (units <= 100) { charge = units * 2.5; } else if (units <= 200) { charge = 100*2.5 + (units-100)*4.0; } - How it works: Different tariffs apply based on usage tiers.
- Uses nested
Exam Tip
Syntax Matters: Always include
{}even for single statements inif-else.- ❌ Wrong:
if (x > 0) printf("Positive"); - ✅ Correct:
if (x > 0) { printf("Positive"); }
- ❌ Wrong:
Trace Conditions: For questions like "What is the output?", trace each condition step-by-step.
- Example:
Output:int x = 1; if (x == 1) printf("One"); else if (x == 2) printf("Two");One(only the first true condition executes).
- Example:
Avoid Redundancy: Combine conditions logically:
- ❌ Redundant:
if (x > 0 && x < 10) { ... } - ✅ Better:
if (x > 0 && x < 10) { ... }(same, but ensure no overlapping cases inswitch).
- ❌ Redundant:
Practice Common Patterns:
- Grade calculators.
- Menu-driven programs.
- Loan/insurance eligibility checks.
Watch for Edge Cases:
- What if
switchhas nodefault? - What if
ifconditions are always true/false?
- What if
Final Note: Selection structures are the backbone of decision-making in programs. Master them by practicing with real-world scenarios (e.g., banking, traffic systems, e-commerce) and always visualize the flow of execution.
Based on the TU BIM syllabus for C Programming (IT232), unit 4.
Discussion
Loading…