Programming In CUnit 49 min read
Decision Making in C: if-else, switch, nested conditions, logical operators
Unit 4 of Programming In C covers how to make programs take decisions using if, else, else if, switch-case, and logical operators (&&, ||, !). You’ll learn how to structure conditions, avoid common pitfalls, and apply decision-making in real-world scenarios like loan approvals, game logic, and menu-driven programs.
Core Concepts
1. Decision-Making Basics
Decision-making in programming allows a program to execute different blocks of code based on certain conditions. The two primary constructs are:
- Conditional Statements:
if,else,else if - Multi-way Branching:
switch-case
How if-else Works
flowchart TD
A["Condition"] -->|"True"| B["Execute if-block"]
A -->|"False"| C["Execute else-block"]
B --> D["End"]
C --> DExample: Loan Approval (Bank Scenario)
#include <stdio.h>
int main() {
float income, loan;
printf("Enter your annual income: ");
scanf("%f", &income);
printf("Enter loan amount: ");
scanf("%f", &loan);
if (income >= 50000) {
if (loan <= 0.8 * income) {
printf("Loan approved!\n");
} else {
printf("Loan denied: Exceeds 80%% of income.\n");
}
} else {
printf("Loan denied: Income too low.\n");
}
return 0;
}
Trace Table:
| Step | income |
loan |
Condition Checked | Output |
|---|---|---|---|---|
| 1 | 60000 | 40000 | income >= 50000 → True |
Proceeds to nested if |
| 2 | 60000 | 40000 | loan <= 0.8 * income → True |
"Loan approved!" |
| 3 | 40000 | 20000 | income >= 50000 → False |
"Loan denied: Income too low" |
2. Logical Operators
Logical operators combine multiple conditions:
&&(AND): Both conditions must be true.||(OR): At least one condition must be true.!(NOT): Inverts the condition.
Example: Daraz Order Status Check
#include <stdio.h>
int main() {
int order_id, stock;
float amount;
printf("Enter order ID: ");
scanf("%d", &order_id);
printf("Enter stock available: ");
scanf("%d", &stock);
printf("Enter order amount: ");
scanf("%f", &amount);
if (order_id > 0 && stock > 0 && amount <= 10000) {
printf("Order processed successfully!\n");
} else {
printf("Order failed: Invalid input.\n");
}
return 0;
}
Trace Table:
order_id |
stock |
amount |
Condition (order_id > 0 && stock > 0 && amount <= 10000) |
Output |
|---|---|---|---|---|
| 101 | 5 | 5000 | True | "Order processed!" |
| -1 | 3 | 8000 | False (first condition fails) | "Order failed" |
3. Nested if-else
Nested if-else allows for hierarchical decision-making. Use it when conditions depend on previous outcomes.
Example: NTC Electricity Bill Calculation
flowchart TD
A["Check if units > 100"] -->|"Yes"| B["Check if units > 200"]
A -->|"No"| C["Bill = units * 2"]
B -->|"Yes"| D["Bill = 200*2 + (units-200)*4"]
B -->|"No"| E["Bill = 100*2 + (units-100)*3"]#include <stdio.h>
int main() {
int units;
printf("Enter electricity units: ");
scanf("%d", &units);
float bill;
if (units > 200) {
bill = 200 * 2 + (units - 200) * 4;
} else if (units > 100) {
bill = 100 * 2 + (units - 100) * 3;
} else {
bill = units * 2;
}
printf("Total bill: Rs. %.2f\n", bill);
return 0;
}
Trace Table:
units |
Condition Checked | Calculation | Output |
|---|---|---|---|
| 50 | units > 200 → False |
bill = 50 * 2 |
Rs. 100.00 |
| 150 | units > 200 → False, units > 100 → True |
bill = 100*2 + (50)*3 |
Rs. 250.00 |
| 250 | units > 200 → True |
bill = 200*2 + (50)*4 |
Rs. 400.00 |
4. switch-case Statement
Use switch-case for multi-way branching when checking a single variable against multiple constant values.
Example: Menu-Driven Program (Khalti Payment Options)
flowchart TD
A["Choose option"] --> B["1: UPI"]
A --> C["2: Debit Card"]
A --> D["3: Credit Card"]
A --> E["4: Exit"]
B --> F["Process UPI"]
C --> F
D --> F
E --> G["End"]#include <stdio.h>
int main() {
int choice;
printf("Khalti Payment Options:\n");
printf("1. UPI\n2. Debit Card\n3. Credit Card\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Processing UPI payment...\n");
break;
case 2:
printf("Processing Debit Card payment...\n");
break;
case 3:
printf("Processing Credit Card payment...\n");
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
return 0;
}
Trace Table:
choice |
Case Matched | Output |
|---|---|---|
| 1 | case 1 |
"Processing UPI payment..." |
| 2 | case 2 |
"Processing Debit Card..." |
| 5 | default |
"Invalid choice!" |
5. Ternary Operator (?:)
A shorthand for simple if-else conditions.
Syntax: condition ? expr1 : expr2
Example: Pathao Driver Availability
#include <stdio.h>
int main() {
int drivers_available = 5;
char status = (drivers_available > 0) ? 'A' : 'N';
printf("Driver status: %c\n", status); // Output: A
return 0;
}
Common Pitfalls and Best Practices
- Missing
breakinswitch-case: Leads to "fall-through" behavior (unintended execution of subsequent cases).switch (x) { case 1: printf("One"); // Missing break → falls to case 2 case 2: printf("Two"); break; } - Uninitialized Variables: Always initialize variables before checking them.
int age; // Uninitialized! if (age > 18) { ... } // Undefined behavior - Overusing Nested
if-else: Can reduce readability. Refactor into functions or useswitch-casewhere applicable.
In the Real World
eSewa Payment Gateway:
- Uses
if-elseto validate user credentials and process payments. - Example: Checks if the user’s bank balance ≥ transaction amount before deducting funds.
if (balance >= amount) { balance -= amount; printf("Payment successful!\n"); } else { printf("Insufficient funds.\n"); }- Uses
Ncell Prepaid Recharge:
- Uses
switch-caseto handle different recharge denominations (e.g., Rs. 100, Rs. 500, Rs. 1000).
switch (denomination) { case 100: add_units(10); break; case 500: add_units(50); break; default: printf("Invalid denomination.\n"); }- Uses
WhatsApp Status Updates:
- Logical operators (
&&,||) determine if a status update is visible to all contacts or only specific ones.
if (is_public && !is_expired) { show_status_to_all(); } else if (!is_public && is_friend) { show_status_to_friends(); }- Logical operators (
Exam Tip
Understand the Flow:
- Always draw a flowchart or trace table for complex
if-elseorswitch-caselogic. Examiners love this! - Example: For a question like "Write a program to find the largest of three numbers," show the decision tree:
flowchart TD A["a > b"] -->|"Yes"| B["a > c"] A -->|"No"| C["b > c"] B -->|"Yes"| D["a is largest"] B -->|"No"| E["c is largest"] C -->|"Yes"| F["b is largest"] C -->|"No"| G["c is largest"]
- Always draw a flowchart or trace table for complex
Practice with Real Scenarios:
- Questions often tie to real-world problems (e.g., "Write a program to calculate NTC bill" or "Check if a user is eligible for a loan").
- Always include input/output examples in your code comments.
Avoid Common Mistakes:
- Off-by-one errors: E.g.,
if (i <= 10)vs.if (i < 10). - Forgotten
breakinswitch: Leads to partial marks if not handled. - Incorrect operator precedence: Use parentheses to clarify logic (e.g.,
if ((x > 0) && (y > 0))).
- Off-by-one errors: E.g.,
Code Structure:
- Indent blocks properly for readability (e.g.,
ifbody,elsebody). - Use meaningful variable names (e.g.,
is_eligibleinstead offlag).
- Indent blocks properly for readability (e.g.,
Visual Summary:
mindmap
root((Decision Making in C))
if-else
syntax["if(condition) { ... } else { ... }"]
nested["if-else inside if-else"]
example["Loan approval, NTC bill"]
switch-case
syntax["switch(var) { case 1: ... break; }"]
fall-through["Missing break causes fall-through"]
example["Khalti payment menu"]
logical operators
AND["&& (both true)"]
OR["|| (either true)"]
NOT["! (inverts condition)"]
example["Daraz order validation"]
ternary
syntax["condition ? expr1 : expr2"]
example["Pathao driver status"]Based on the PU BE Computer (PU) syllabus for Programming In C, unit 4.
Discussion
Loading…