CodeBlanks Logo Icon CodeBlanks

Menu loop

Write a menu loop with switch-case.

while and switch for a menu

So far the calculator ran all operations one after another. A real calculator lets the user pick an operation from a menu. We use a while loop and a switch statement:

int choice = 1;
while (choice != 0) {
    switch (choice) {
        case 1: ... break;
        case 2: ... break;
        default: break;
    }
    choice = 0;
}

while runs the loop, switch executes the branch for the choice.

The switch statement

The switch statement runs different branches based on a variable's value:

switch (choice) {
    case 1: add(...); break;
    case 2: subtract(...); break;
    default: break;
}

Each case needs a break at the end; otherwise execution falls through to the next case. default runs when no case matches.

Practice Add a menu loop

Modify main in the code below: replace the printf calls with a while loop and switch. Start with int choice = 1;, include case 1: printf("%d\n", add(5, 3)); break; and case 2: printf("%d\n", subtract(5, 3)); break;, plus default: break; and choice = 0; at the end. Keep printf("Calculator\n"); as the header.

Starter code

main.c
#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

int subtract(int a, int b) {
    return a - b;
}

int multiply(int a, int b) {
    return a * b;
}

int divide(int a, int b) {
    if (b == 0) return 0;
    return a / b;
}

int main(void) {
    printf("Calculator\n");
    printf("%d\n", add(5, 3));
    printf("%d\n", subtract(5, 3));
    printf("%d\n", multiply(5, 3));
    printf("%d", divide(6, 3));
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

int subtract(int a, int b) {
    return a - b;
}

int multiply(int a, int b) {
    return a * b;
}

int divide(int a, int b) {
    if (b == 0) return 0;
    return a / b;
}

int main(void) {
    printf("Calculator\n");
    int choice = 1;
    while (choice != 0) {
        switch (choice) {
            case 1: printf("%d\n", add(5, 3)); break;
            case 2: printf("%d\n", subtract(5, 3)); break;
            default: break;
        }
        choice = 0;
    }
    return 0;
}

Expected output

Calculator
8

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Best loop for a menu?

  • for
  • do-while
  • while Correct answer
  • foreach

Explanation: while loops as long as the condition holds; it suits a menu.

2 Loop condition

Question
while (____) { ... }
Answer
while (choice != 0) { ... }

Explanation: choice != 0 keeps the loop running until choice becomes 0.

3 What does break do in switch?

  • Starts the loop
  • Falls to next case
  • Goes to default
  • Exits the switch Correct answer

Explanation: break exits the switch and prevents falling to the next case.

All lessons in Beginner