What are Menu Driven Switch Programs- Free C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course • Control Statements

Menu Driven Switch Programs

Normalise input with tolower, then build a complete menu driven program in C using an endless loop and a switch, the same pattern used in embedded consoles and test tools.

Menu Driven Program in C

A menu driven program in C shows the user a list of options, reads a choice, performs the matching action, and repeats until the user asks to quit. The switch statement is the natural engine for it. In this lesson of our free C programming course you will first learn a trick that shortens long case lists, and then build a complete LED control menu that mirrors how serial consoles and bench-test utilities work in embedded C programming.

Everything in this free C tutorial is original code you can compile on any Linux, macOS or Windows machine with GCC.

Topics Covered

menu driven program in C tolower and ctype.h infinite loop with switch exit flag free embedded C course

What You Will Learn

In this lecture you will:

  • Use a function call as the switch expression.
  • Apply tolower to treat upper and lower case letters alike.
  • Combine while and switch into a working menu.
  • Stop the menu cleanly with a flag, and understand why break alone is not enough.
  • Keep state between menu choices.
  • Handle invalid choices and closed input.

Prerequisites

Complete the earlier lectures on switch basics, break and case grouping, and be comfortable with the while loop. A basic idea of what a function call returns is enough for the tolower section.

The Switch Expression Can Be a Function Call

The controlling expression of a switch does not have to be a plain variable. Any expression that produces an integer works, including the return value of a function. That fact lets you shrink a ten-label switch down to five. Instead of writing separate labels for 'a' and 'A', convert the character first and switch on the converted value.

The standard function for this is tolower() from <ctype.h>. It returns the lowercase version of an uppercase letter and leaves every other character unchanged.

Example 1: Vowel or Consonant, Any Case

#include <ctype.h>
#include <stdio.h>

int main(void)
{
    int ch;

    printf("Type one letter: ");
    ch = getchar();
    if (ch == EOF || !isalpha((unsigned char)ch)) {
        printf("That is not a letter\n");
        return 1;
    }

    switch (tolower((unsigned char)ch)) {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
        printf("'%c' is a vowel\n", ch);
        break;
    default:
        printf("'%c' is a consonant\n", ch);
        break;
    }
    return 0;
}
gcc -std=c17 -Wall -Wextra -o ep_vowel ep_vowel.c
./ep_vowel
Type one letter: E
'E' is a vowel

Type one letter: k
'k' is a consonant

Type one letter: 7
That is not a letter
Input flow in the vowel checker
getchar()→ isalpha check
↓ letters only
tolower(ch)→ E becomes e
↓
switch: a e i o u→ voweldefault→ consonant
Why the unsigned char cast? The ctype functions accept either an unsigned char value or EOF. Passing a plain negative char is undefined behaviour on platforms where char is signed. The cast is a small habit that prevents rare, hard-to-find bugs, and the explicit isalpha check stops digits and symbols from being called “consonants”.

Building a Menu Driven Program

The menu pattern has four parts. A loop keeps the program alive. Inside it, the program prints the options and reads a choice. A switch runs the selected action. One special choice changes a variable that makes the loop condition false. Embedded engineers use exactly this skeleton for UART debug consoles, factory test firmware and bootloader command prompts.

Menu loop structure
while (running)
↓
Print menu→ Read choice
↓
switch (choice)→ run action→ break
↓
Choice 0 sets running = 0→ loop ends, program exits

Example 2: LED Control Menu

#include <stdio.h>

int main(void)
{
    int running = 1;
    int led_on = 0;
    int choice;

    while (running) {
        printf("\n--- LED Control ---\n");
        printf("1. Turn ON\n");
        printf("2. Turn OFF\n");
        printf("3. Toggle\n");
        printf("4. Show status\n");
        printf("0. Exit\n");
        printf("Choice: ");

        if (scanf("%d", &choice) != 1) {
            printf("Input closed, leaving\n");
            break;
        }

        switch (choice) {
        case 1:
            led_on = 1;
            printf("LED is now ON\n");
            break;
        case 2:
            led_on = 0;
            printf("LED is now OFF\n");
            break;
        case 3:
            led_on = !led_on;
            printf("LED toggled to %s\n", led_on ? "ON" : "OFF");
            break;
        case 4:
            printf("LED status: %s\n", led_on ? "ON" : "OFF");
            break;
        case 0:
            running = 0;
            break;
        default:
            printf("Invalid choice %d\n", choice);
            break;
        }
    }
    printf("Goodbye\n");
    return 0;
}

The LED here is simulated by the variable led_on. On real hardware each case would call a GPIO function instead, but the control structure stays identical. Build it and feed a scripted sequence of choices:

gcc -std=c17 -Wall -Wextra -o ep_menu ep_menu.c
printf '1\n4\n3\n4\n7\n0\n' | ./ep_menu

Expected output (the menu text repeats before each prompt; only the first full menu is shown, followed by the replies to each choice):

--- LED Control ---
1. Turn ON
2. Turn OFF
3. Toggle
4. Show status
0. Exit
Choice: LED is now ON
...
Choice: LED status: ON
...
Choice: LED toggled to OFF
...
Choice: LED status: OFF
...
Choice: Invalid choice 7
...
Choice: Goodbye

Run it interactively too and type a letter instead of a number. The scanf return check catches that, prints the closing message and leaves the loop, instead of spinning forever on bad input.

Why the Menu Needs an Exit Flag

Beginners often write case 0: break; and wonder why the menu never closes. The break leaves only the switch, and then the loop starts its next round. Choice 0 must change something the loop can see. A flag such as running is the clearest solution. Alternatives are calling return from main, or exit(0), which are fine in small tools but skip any cleanup code placed after the loop. A flag keeps one exit path and makes the cleanup (closing files, switching off pins) easy to add.

Infinite Loop Variants

StyleExit methodWhen to use
while (running)Set flag to 0General programs, cleanup needed
while (1) with returnreturn in the exit caseVery small tools
for (;;) in firmwareNever exitsBare-metal main loop that runs until power-off

Real-World Uses

  • Serial debug consoles: type a number over UART to read a sensor or reboot a module.
  • Production test jigs: each menu entry exercises one peripheral.
  • Bootloaders: choose to boot, update firmware or dump memory.
  • Learning projects: inventory, bank or student record programs for practice.

Common Mistakes and Troubleshooting

MistakeSymptomFix
Exit case contains only breakMenu never endsSet a flag or return
No scanf check, user types a letterEndless loop printing the menuTest the return value, then leave or clear input
State variable declared inside the loopLED state forgotten each roundDeclare it before the loop
Missing defaultInvalid numbers silently ignoredPrint an error message
Calling tolower on raw charUndefined behaviour with negative valuesCast to unsigned char

Best Practices

  • Keep the menu text in one place and show it every round.
  • Move long actions into separate functions so each case stays two or three lines.
  • Use an enum for choices in larger programs, such as CMD_LED_ON, to avoid magic numbers.
  • Always handle the invalid input path; it is where field failures start.
  • On a microcontroller, never block forever waiting for input if other tasks must run; poll instead.

Performance Note

A switch with dense small integers is usually compiled into a jump table, so selecting an action takes constant time however many menu entries you add. Printing the menu with printf costs far more than the dispatch itself.

Summary and Key Takeaways

  • The switch expression can be a function call such as tolower(ch).
  • Normalising input shortens label lists and prevents case-sensitivity bugs.
  • A menu is a loop plus a switch plus an exit condition.
  • break inside a switch never ends the loop; use a flag, return or exit.
  • Check scanf results and always provide a default message.

You have now covered every switch topic in this chapter. The final lecture is a quiz and interview question set to test everything.

Frequently Asked Questions

What is a menu driven program in C?

It is a program that displays options, reads the user’s choice and runs the matching action inside a loop until the user selects exit.

Why use switch for menus?

Each option maps to one constant value, so a switch is cleaner and often faster than a long if-else ladder.

How do I exit a loop from inside a switch?

Set a flag variable that the loop condition checks, or use return. A break inside the switch only leaves the switch.

What does tolower do in C?

It converts an uppercase letter to lowercase and returns other characters unchanged. It is declared in ctype.h.

Can the switch expression be a function call?

Yes, as long as the function returns an integer type. The call is evaluated once before matching.

Is a menu driven program used in embedded systems?

Yes. Serial consoles, bootloader prompts and factory test tools all use the same menu and switch pattern.

Suggested Images

  • Menu loop flowchart: ALT “menu driven program in C flowchart free C programming course”.
  • Serial terminal showing LED menu: ALT “embedded C programming UART menu switch example”.
  • tolower conversion illustration: ALT “tolower switch vowel checker free C tutorial”.

Test Yourself Next

The next lecture is a quiz and interview question set that completes the switch topic in our free embedded C course.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →