(Learn C Programming for Beginners — Day 9)
Welcome to Day 9 of your 30-Day C Programming Adventure! 🚀
Yesterday, we learned how to make decisions using if and else. It works great for simple checks like "Is the number positive?" or "Is the user an adult?".
But what if you have a menu with 5, 10, or 20 options? Writing 20 else if statements is messy, hard to read, and frankly, a bit ugly.
Enter the Switch Statement. It’s the cleaner, more organized cousin of the if-else ladder, designed specifically for handling multiple choices.
By the end of this post, you'll be able to build clean menu-driven programs like a vending machine or a game menu.
🎯 Goals for Today
- Understand
switch— How it works and when to use it. - The
caseKeyword — Defining the options. - The
breakKeyword — Why it's critical (and what happens if you forget it). - The
defaultKeyword — The safety net. - Build a "Vending Machine" — A program that dispenses virtual snacks.
🎛️ The Switch Syntax
The switch statement takes a variable and checks it against a list of values (cases).
switch (variable) {
case value1:
// Code to run if variable == value1
break;
case value2:
// Code to run if variable == value2
break;
default:
// Code to run if variable doesn't match ANY case
}
Key Rules:
- The variable must be an integer (
int) or a character (char). You cannot switch on strings or floats. breakis essential. It tells C to stop executing code and exit the switch block. Without it, C will "fall through" and execute the next case too!defaultis optional but recommended. It handles invalid inputs.
🆚 Switch vs. Else-If
Use if-else when:
* You are checking ranges (e.g., score > 50 && score < 90).
* You are checking complex conditions.
* You are working with floats.
Use switch when:
* You are checking a single variable against specific, constant values (e.g., option == 1, grade == 'A').
* You want to build a menu system.
💻 Let's Code: The "Virtual Vending Machine"
Let's build a program that displays a menu of snacks and asks the user to choose one by entering a number.
Step 1: Create day9_switch.c.
Step 2: Type this code:
/*
Project: Virtual Vending Machine
Description: Demonstrates the switch statement for menu selection.
*/
#include <stdio.h>
int main() {
int choice;
// 1. Display Menu
printf("=============================\n");
printf(" VIRTUAL VENDING MACHINE \n");
printf("=============================\n");
printf("1. Cola ($1.50)\n");
printf("2. Green Tea ($1.00)\n");
printf("3. Chocolate ($2.00)\n");
printf("4. Chips ($1.25)\n");
printf("=============================\n");
// 2. Get User Choice
printf("Enter the number of your choice: ");
scanf("%d", &choice);
// 3. Handle Choice with Switch
switch (choice) {
case 1:
printf("\nDispensing Cola... 🥤\n");
printf("That will be $1.50.\n");
break; // Stop here!
case 2:
printf("\nDispensing Green Tea... 🍵\n");
printf("That will be $1.00.\n");
break;
case 3:
printf("\nDispensing Chocolate... 🍫\n");
printf("That will be $2.00.\n");
break;
case 4:
printf("\nDispensing Chips... 🥔\n");
printf("That will be $1.25.\n");
break;
default:
// This runs if the user enters 5, 0, -1, etc.
printf("\n❌ Invalid selection! Please choose 1-4.\n");
}
printf("\nThank you! Have a nice day.\n");
return 0;
}
Step 3: Compile and Run!
* gcc day9_switch.c -o day9_switch
* ./day9_switch
⚠️ The "Fall-Through" Trap
What happens if you remove the break; statements?
If the user selects 1, the program will print "Dispensing Cola", AND THEN it will continue down and print "Dispensing Green Tea", "Dispensing Chocolate", etc., until it hits a break or the end.
Sometimes this is useful (e.g., "Case 1, 2, and 3 all get the same prize"), but usually, it's a bug. Always double-check your breaks!
📝 Day 9 Summary
switchis perfect for menus and specific value checks.casedefines the options.breakstops the code from running into the next case.defaulthandles anything that doesn't match.- Only works with integers and characters.
🚀 Challenge for Tomorrow
Create a "Day of the Week" program:
1. Ask the user to enter a number (1-7).
2. Use a switch statement to print the corresponding day (1 = Monday, 7 = Sunday).
3. Add a default case for invalid numbers.
Next Up: Day 10: Loops Part 1 — We'll learn how to make the computer do the heavy lifting by repeating tasks automatically!
Found this helpful? Clap 👏 and follow to keep up with the adventure!
Comments
Post a Comment