Skip to main content

C Programming Day 9: The Switch Statement - Handling Multiple Choices

(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

  1. Understand switch — How it works and when to use it.
  2. The case Keyword — Defining the options.
  3. The break Keyword — Why it's critical (and what happens if you forget it).
  4. The default Keyword — The safety net.
  5. 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:

  1. The variable must be an integer (int) or a character (char). You cannot switch on strings or floats.
  2. break is 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!
  3. default is 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

  • switch is perfect for menus and specific value checks.
  • case defines the options.
  • break stops the code from running into the next case.
  • default handles 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!

CProgramming #CodingForBeginners #LearnToCode #Programming #Developer

Comments

Popular posts from this blog

Unlock C Programming in 30 Days

Your 30‑Day C Programming Series Click any day below to jump straight to that lesson (opens in a new tab): Day 0: Unlock C Programming in 30 Days Your ultimate self‑study guide introduction—your roadmap for the entire 30‑day journey. Read Day 0 Day 1: What is Programming & Setting Up Your C Lab Understand programming basics and install GCC + VS Code so you’re ready to code. Read Day 1 Day 2: Write Your First “Hello, World!” Learn the anatomy of a C program and compile & run your very first C code . Read Day 2 Day 3: Variables & Basic Data Types Discover how to store and print integers, floats, and characters in C . Read Day 3 Day 4: Interactive Input with scanf Make your programs listen—read numbers, floats, and chars from the user. Read Day 4

C Programming Day 3: Variables, Data Types & Constants - The "Boxes" of Programming

(Learn C Programming for Beginners — Day 3) Welcome back to your 30-Day C Programming Adventure ! 🚀 Yesterday, you wrote your very first "Hello, World!" program. You felt the power of making the computer speak. Today, we’re going to give your programs a memory. Imagine trying to cook a complex meal without any bowls or containers. You’d have ingredients everywhere! In programming, variables are those containers. They hold your data so you can use, change, and display it. Today, we unlock the power of Variables , Data Types , and Constants . By the end of this post, you'll be able to write programs that can store and manipulate information, not just print static text. 🎯 Goals for Today Understand Variables — What they are and how to create them. Master Data Types — Integers, floats, characters, and more. Learn Constants — Values that never change. Write Code — Create a program that stores and prints different types of data. 📦 What is a Varia...

C Programming Day 4: Input/Output - Talking to Your Computer

(Learn C Programming for Beginners — Day 4) Welcome to Day 4 of your 30-Day C Programming Adventure ! 🚀 So far, our programs have been a bit... quiet. We've told the computer what to store (variables) and what to show us ( printf ), but we haven't let the user say anything back. It's been a one-way conversation. Today, that changes. We are going to make your programs interactive . By the end of this post, you'll be able to write programs that ask questions, listen for answers, and respond accordingly. We're diving deep into printf (Output) and its best friend, scanf (Input). 🎯 Goals for Today Master printf — Learn how to format output beautifully. Unlock scanf — Learn how to take input from the user. Handle Common Pitfalls — Avoid the dreaded "skipped input" bug. Build an Interactive Program — Create a " Age Calculator " that talks to you. 📢 The Art of Speaking: printf Revisited You've used printf to print...