C ProgrammingUnit 411 min read
Control Structures: Selection (if, switch, nested conditions)
Unit 4 of C Programming introduces decision-making logic using if, else if, else, switch, and nested conditions to control program flow based on conditions, enabling dynamic behavior in applications.
TAKEAWAYS:
- Learn how
if,else if, andelsestatements execute code blocks conditionally based on boolean expressions. - Understand the
switchstatement for multi-way branching and its efficiency compared to nestedif-else. - Master nested conditions to handle complex decision-making scenarios.
- Recognize logical operators (
&&,||,!) and their role in combining conditions. - Apply selection structures to real-world problems like loan eligibility, discount calculations, and user input validation.
- Avoid common pitfalls like missing braces, redundant conditions, and infinite loops due to incorrect logic.
1. Introduction to Control Structures (Selection)
Control structures allow a program to make decisions and execute different blocks of code based on conditions. In C, selection structures include:
- Single
ifstatement if-elsestatementelse ifladderswitch-casestatement- Nested conditions
These structures enable dynamic execution paths, making programs adapt to user input or data.
2. The if Statement
The simplest selection structure checks a condition and executes a block if true.
Syntax
if (condition) {
// Code to execute if condition is true
}
How It Works
- The
conditionis evaluated as a boolean (true/false). - If
true, the block inside{}runs; otherwise, it skips.
Example: Check if a number is positive
flowchart TD
A["Start"] --> B{"Is number > 0?"}
B -->|"Yes"| C["Print 'Positive'"]
B -->|"No"| D["Print 'Non-positive'"]
C --> E["End"]
D --> ECode Example
#include <stdio.h>
int main() {
int num = 5;
if (num > 0) {
printf("%d is positive.\n", num);
}
return 0;
}
Output:
5 is positive.
Trace Table
| Step | Condition (num > 0) |
Action |
|---|---|---|
| 1 | 5 > 0 (true) |
Print "Positive" |
3. The if-else Statement
Adds an alternative block when the condition is false.
Syntax
if (condition) {
// Code if true
} else {
// Code if false
}
Example: Check even/odd
flowchart TD
A["Start"] --> B{"Is number % 2 == 0?"}
B -->|"Yes"| C["Print 'Even'"]
B -->|"No"| D["Print 'Odd'"]
C --> E["End"]
D --> ECode Example
#include <stdio.h>
int main() {
int num = 7;
if (num % 2 == 0) {
printf("%d is even.\n", num);
} else {
printf("%d is odd.\n", num);
}
return 0;
}
Output:
7 is odd.
Trace Table
| Step | Condition (num % 2 == 0) |
Action |
|---|---|---|
| 1 | 7 % 2 == 0 (false) |
Print "Odd" |
4. else if Ladder
Handles multiple conditions sequentially.
Syntax
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Default code
}
Example: Grade classification
flowchart TD
A["Start"] --> B{"Marks >= 80?"}
B -->|"Yes"| C["Print 'A'"]
B -->|"No"| D{"Marks >= 60?"}
D -->|"Yes"| E["Print 'B'"]
D -->|"No"| F{"Marks >= 40?"}
F -->|"Yes"| G["Print 'C'"]
F -->|"No"| H["Print 'Fail'"]
C --> I["End"]
E --> I
G --> I
H --> ICode Example
#include <stdio.h>
int main() {
int marks = 75;
if (marks >= 80) {
printf("Grade: A\n");
} else if (marks >= 60) {
printf("Grade: B\n");
} else if (marks >= 40) {
printf("Grade: C\n");
} else {
printf("Grade: Fail\n");
}
return 0;
}
Output:
Grade: B
Trace Table
| Step | Condition (marks >= 80) |
Condition (marks >= 60) |
Action |
|---|---|---|---|
| 1 | 75 >= 80 (false) |
75 >= 60 (true) |
Print "B" |
5. The switch-case Statement
Efficient for multi-way branching (e.g., menu-driven programs).
Syntax
switch (expression) {
case value1:
// Code if expression == value1
break;
case value2:
// Code if expression == value2
break;
default:
// Default code
}
Key Points
expressionmust be an integer,char, or enum.breakexits theswitch; without it, execution "falls through."defaultruns if no case matches.
Example: Day of the week
flowchart TD
A["Start"] --> B["Input day (1-7)"]
B --> C{"day == 1?"}
C -->|"Yes"| D["Print 'Monday'"]
C -->|"No"| E{"day == 2?"}
E -->|"Yes"| F["Print 'Tuesday'"]
E -->|"No"| G{"day == 3?"}
G -->|"Yes"| H["Print 'Wednesday'"]
G -->|"No"| I{"day == 4?"}
I -->|"Yes"| J["Print 'Thursday'"]
I -->|"No"| K{"day == 5?"}
K -->|"Yes"| L["Print 'Friday'"]
K -->|"No"| M{"day == 6?"}
M -->|"Yes"| N["Print 'Saturday'"]
M -->|"No"| O["Print 'Sunday'"]
D --> P["End"]
F --> P
H --> P
J --> P
L --> P
N --> P
O --> PCode Example
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
Output:
Wednesday
Trace Table
| Step | day |
Case Match | Action |
|---|---|---|---|
| 1 | 3 |
case 3 |
Print "Wednesday" |
6. Nested Conditions
Combines multiple if-else or switch statements for complex logic.
Example: Loan eligibility
flowchart TD
A["Start"] --> B{"Income >= 30000?"}
B -->|"Yes"| C{"Credit score >= 700?"}
C -->|"Yes"| D["Approve loan"]
C -->|"No"| E["Reject loan"]
B -->|"No"| F["Reject loan"]
D --> G["End"]
E --> G
F --> GCode Example
#include <stdio.h>
int main() {
int income = 35000, credit_score = 750;
if (income >= 30000) {
if (credit_score >= 700) {
printf("Loan approved!\n");
} else {
printf("Loan rejected: Low credit score.\n");
}
} else {
printf("Loan rejected: Insufficient income.\n");
}
return 0;
}
Output:
Loan approved!
Trace Table
| Step | Condition (income >= 30000) |
Condition (credit_score >= 700) |
Action |
|---|---|---|---|
| 1 | 35000 >= 30000 (true) |
750 >= 700 (true) |
Print "Approved!" |
7. Logical Operators
Combine conditions using:
&&(AND): Both must be true.||(OR): At least one must be true.!(NOT): Inverts the condition.
Example: Check if a number is between 10 and 20
if (num > 10 && num < 20) {
printf("Number is between 10 and 20.\n");
}
Truth Table for Logical Operators
| A | B | A && B | A || B | !A |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
8. Comparison Table: if-else vs switch
| Feature | if-else |
switch-case |
|---|---|---|
| Use Case | Single/multiple conditions | Multi-way branching (fixed values) |
| Performance | Slower for many cases | Faster (jump table) |
| Expression Type | Any boolean expression | Integer/char/enum |
| Flexibility | Handles ranges (>=, <=) |
Only exact matches |
| Readability | Better for complex conditions | Better for enumerated values |
9. Common Pitfalls
- Missing braces: Causes syntax errors.
if (x > 0) printf("Positive"); // Error: No braces! - Infinite loops: Incorrect conditions (e.g.,
while (1)). - Redundant conditions: Overlapping
else ifclauses. - Forgotten
break: Fall-through inswitch.
10. Real-World Applications
In the Real World
eSewa/Khalti Payment Gateways
- Idea Used:
switch-casefor transaction types (e.g., bill payment, recharge, transfer). - How: When a user selects "Electricity Bill," the system uses a
switchto route the payment to the correct utility provider (NESA, NEA, etc.). - Worked Example:
switch (transaction_type) { case BILL_PAYMENT: if (provider == ELECTRICITY) { /* Route to NESA */ } break; case RECHARGE: /* Route to NTC/Ncell */ break; default: /* Error */ break; }
- Idea Used:
Daraz Order Processing
- Idea Used: Nested
if-elsefor order validation. - How: Daraz checks:
- Is the user logged in? (
if (logged_in)) - Is the item in stock? (
else if (stock > 0)) - Is the payment successful? (
else if (payment_confirmed))
- Is the user logged in? (
- Worked Example:
if (user_logged_in) { if (item_stock > 0) { if (payment_successful) { printf("Order confirmed!\n"); } else { printf("Payment failed.\n"); } } else { printf("Out of stock.\n"); } } else { printf("Login required.\n"); }
- Idea Used: Nested
Pathao Ride Booking
- Idea Used:
switchfor ride type selection. - How: When a user taps "Car," "Bike," or "Van," Pathao uses a
switchto:- Show available drivers.
- Calculate fare dynamically.
- Apply discounts (e.g., early morning rides).
- Worked Example:
switch (ride_type) { case CAR: fare = 150 + (distance * 2); break; case BIKE: fare = 100 + (distance * 1.5); break; case VAN: fare = 200 + (distance * 3); break; default: printf("Invalid ride type.\n"); }
- Idea Used:
11. Exam Tips
- Understand Syntax: Know the exact structure of
if,else if,else, andswitch. - Trace Logic: Always draw flowcharts or trace tables for nested conditions.
- Practice Errors: Write code with common mistakes (missing braces, incorrect operators) and fix them.
- Real-World Mapping: Relate selection structures to scenarios like:
- Bank loans:
if (income >= threshold) { approve(); } - NEPSE trading:
switch (order_type) { case BUY; case SELL; } - NTC/Ncell tariffs:
if (minutes_used > 100) { apply_discount(); }
- Bank loans:
- Avoid Overcomplicating: Use
switchonly for fixed values; preferif-elsefor ranges. - Memory Layout: For nested conditions, visualize the decision tree (like the Daraz order example above).
Example Exam Question:
Write a C program that takes a student's marks (out of 100) and prints:
- "A" if marks >= 80,
- "B" if marks >= 60,
- "C" if marks >= 40,
- "Fail" otherwise.
Also, handle invalid input (marks < 0 or > 100) by printing "Invalid marks."
Expected Solution:
#include <stdio.h>
int main() {
int marks;
printf("Enter marks: ");
scanf("%d", &marks);
if (marks < 0 || marks > 100) {
printf("Invalid marks.\n");
} else if (marks >= 80) {
printf("Grade: A\n");
} else if (marks >= 60) {
printf("Grade: B\n");
} else if (marks >= 40) {
printf("Grade: C\n");
} else {
printf("Grade: Fail\n");
}
return 0;
}
Based on the TU BITM syllabus for C Programming (IT232), unit 4.
Discussion
Loading…