Structured Programming in CUnit 1010 min read
Menu-Driven Programs & Switch-Case: Design, Logic, and Real-World Applications
Unit 10 of Structured Programming in C teaches how to create interactive menu-driven programs using switch-case statements, loop integration, and modular design—essential for building user-friendly applications like banking systems, order processing, or utility bill calculators.
TAKEAWAYS:
- A menu-driven program uses loops and
switch-caseto repeatedly offer users choices until they exit. - The
switch-casestructure replaces longif-elsechains for multi-way branching, improving readability. - Input validation (e.g., checking for numeric inputs) prevents crashes from invalid user choices.
- Real-world apps (e.g., eSewa’s payment menus, Daraz’s order status) rely on this pattern for intuitive UIs.
- Modularity (separating logic into functions) makes menu-driven programs easier to debug and extend.
- Always include a default case in
switchto handle unexpected inputs gracefully.
1. Why Menu-Driven Programs?
Menu-driven programs are the backbone of interactive applications where users repeatedly select options. They:
- Provide a user-friendly interface (e.g., ATM machines, restaurant ordering systems).
- Reduce code redundancy by reusing logic via loops.
- Make programs scalable (easy to add new features without rewriting core logic).
How It Works
- Display a menu (e.g., options 1–5).
- Prompt for user input (e.g.,
Enter choice:). - Validate input (ensure it’s within the menu range).
- Execute the chosen operation using
switch-case. - Loop back to the menu until the user exits.
2. The switch-case Statement
The switch-case is a multi-way branch that replaces nested if-else for cleaner code when checking a single variable against multiple constants.
Syntax
switch (expression) {
case constant1:
// Code for case 1
break;
case constant2:
// Code for case 2
break;
...
default:
// Code if no case matches
}
Key Rules
- The
expressionmust be an integer, character, or enum. - Each
casemust end with abreak(unless intentional fall-through is needed). - The
defaultcase is optional but highly recommended for error handling.
3. Visual: How switch-case Executes
flowchart TD
A["Start"] --> B["Evaluate expression"]
B --> C{"expression == case1?"}
C -->|"Yes"| D["Execute case1\nbreak"]
C -->|"No"| E{"expression == case2?"}
E -->|"Yes"| F["Execute case2\nbreak"]
E -->|"No"| G{"expression == caseN?"}
G -->|"Yes"| H["Execute caseN\nbreak"]
G -->|"No"| I["Execute default"]4. Worked Example: Menu for Basic Arithmetic
Problem: Create a menu-driven program to perform addition, subtraction, multiplication, or division of two numbers.
Step-by-Step Code
#include <stdio.h>
int main() {
int choice, num1, num2, result;
char continueChoice;
do {
printf("\n--- Menu ---\n");
printf("1. Add\n");
printf("2. Subtract\n");
printf("3. Multiply\n");
printf("4. Divide\n");
printf("5. Exit\n");
printf("Enter choice (1-5): ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
result = num1 + num2;
printf("Sum: %d\n", result);
break;
case 2:
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
result = num1 - num2;
printf("Difference: %d\n", result);
break;
case 3:
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
result = num1 * num2;
printf("Product: %d\n", result);
break;
case 4:
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
if (num2 == 0) {
printf("Error: Division by zero!\n");
} else {
result = num1 / num2;
printf("Quotient: %d\n", result);
}
break;
case 5:
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
printf("Continue? (y/n): ");
scanf(" %c", &continueChoice);
} while (continueChoice == 'y' || continueChoice == 'Y');
return 0;
}
Trace: Execution Flow
| Step | Action | Output/State |
|---|---|---|
| 1 | Display menu | --- Menu --- |
| 2 | User enters 3 |
Enter choice (1-5): 3 |
| 3 | switch(3) matches case 3 |
Prompts for two numbers |
| 4 | User enters 5 4 |
Product: 20 |
| 5 | Loop continues (y) |
Menu redisplays |
| 6 | User enters 5 |
Exiting... |
5. Input Validation: Handling Invalid Choices
Problem: What if the user enters 6 or a non-integer?
Solution: Use while loops to validate input.
Code Snippet for Validation
int choice;
printf("Enter choice (1-5): ");
while (1) {
if (scanf("%d", &choice) != 1) {
printf("Invalid input! Enter a number: ");
while (getchar() != '\n'); // Clear invalid input
} else if (choice < 1 || choice > 5) {
printf("Choice out of range! Enter 1-5: ");
} else {
break; // Valid input
}
}
Visual: Input Validation Flow
flowchart TD
A["Prompt for choice"] --> B["Read input"]
B --> C{"Input valid?"}
C -->|"No"| D["Clear buffer\nReprompt"]
C -->|"Yes"| E{"Choice in 1-5?"}
E -->|"No"| D
E -->|"Yes"| F["Proceed to switch"]6. Real-World Applications
Example 1: eSewa Payment Menu
- Idea Used:
switch-casefor transaction types (electricity, phone, loan). - How It Works:
- User selects
1for electricity bill →switch(1)calls the bill payment function. - Invalid input (e.g.,
0) triggers thedefaultcase: "Invalid option. Try again."
- User selects
Example 2: Daraz Order Status System
- Idea Used: Menu-driven loop with
switch-casefor order tracking. - How It Works:
- Menu options:
- Check order status
- Cancel order
- View order history
- Each option updates a queue (FIFO) of order IDs for processing.
- Menu options:
Example 3: NTC Bill Calculator (Worked Example)
Scenario: NTC charges Rs. 100 for the first 50 units and Rs. 150 for every additional 100 units. Write a menu-driven program to:
- Calculate bill for given units.
- Show usage history.
- Exit.
Code:
#include <stdio.h>
void calculateBill(int units) {
float bill = 0;
if (units <= 50) {
bill = 100;
} else {
bill = 100 + (units - 50) / 100 * 150;
}
printf("Bill: Rs. %.2f\n", bill);
}
int main() {
int choice, units;
do {
printf("\n--- NTC Bill Calculator ---\n");
printf("1. Calculate Bill\n");
printf("2. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter units consumed: ");
scanf("%d", &units);
calculateBill(units);
break;
case 2:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 2);
return 0;
}
7. Advantages and Disadvantages
| Advantages | Disadvantages |
|---|---|
Cleaner code than nested if-else |
Limited to constant expressions |
| Easy to extend (add new cases) | No range checks in case (must use if) |
| Improves user experience with menus | Requires break to avoid fall-through |
| Reusable for similar operations | Default case must be handled explicitly |
8. Common Pitfalls and Fixes
| Pitfall | Fix |
|---|---|
Missing break in case |
Add break to prevent fall-through |
No default case |
Add default: printf("Error!"); |
| Input not validated | Use while loops to check ranges |
| Forgetting to clear input buffer | Use while (getchar() != '\n'); |
| Hardcoding menu options | Store options in an array for flexibility |
9. Exam Tip
Structure Your Answer:
- Always start with a
do-whileloop for the menu. - Use
switch-casefor multi-option menus. - Include a
defaultcase (marks are deducted if omitted!).
- Always start with a
Input Validation is Key:
- Examiners check if you handle invalid inputs (e.g., letters, out-of-range numbers).
- Use
whileloops to re-prompt until valid input is received.
Modularity Earns Extra Marks:
- Break logic into functions (e.g.,
calculateSum(),displayMenu()). - Example: In the NTC bill calculator,
calculateBill()is a separate function.
- Break logic into functions (e.g.,
Trace Your Code:
- For 5 marks, show a step-by-step trace (like the table above) for a sample input (e.g., choice
3, then5 4).
- For 5 marks, show a step-by-step trace (like the table above) for a sample input (e.g., choice
Real-World Tie-In:
- Relate your program to a known system (e.g., "This is like the menu in eSewa where users select payment options").
10. Practice Questions
Write a menu-driven program to:
- Convert Celsius to Fahrenheit.
- Convert Fahrenheit to Celsius.
- Exit.
Hint: Use
switch-caseand validate temperature inputs.
Extend the NTC bill calculator to include:
- A
case 3for "Show past bills" (store bills in an array). - Input validation for negative units.
- A
Debug the following code snippet:
switch (choice) { case 1: printf("Add\n"); case 2: printf("Subtract\n"); // Missing break! default: printf("Invalid\n"); }What happens if
choice = 1? How to fix it?
Based on the TU BITM syllabus for Structured Programming in C (ITM102), unit 10.
Discussion
Loading…