C PROGRAMMING PROGRAM • SWITCH & MENU PROGRAMS

Use a Nested switch for Shape Calculations

Learn how to use a nested switch for shape calculations using a clear C program.

IntermediateNested switchAreaPerimeter

PROBLEM UNDERSTANDING

Input and expected output

Sample input
1
2
6
Sample output
Result = 24.00

COMPLETE C PROGRAM

Complete C implementation

nested-switch-shape-menu.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int shape, operation;
    double value;
    printf("Shape: 1. Square  2. Circle: ");
    scanf("%d", &shape);
    printf("Operation: 1. Area  2. Perimeter: ");
    scanf("%d", &operation);
    printf("Enter side or radius: ");
    scanf("%lf", &value);
    switch (shape) {
        case 1:
            switch (operation) {
                case 1: printf("Result = %.2f\n", value * value); break;
                case 2: printf("Result = %.2f\n", 4.0 * value); break;
                default: puts("Invalid operation.");
            }
            break;
        case 2:
            switch (operation) {
                case 1: printf("Result = %.2f\n", 3.141592653589793 * value * value); break;
                case 2: printf("Result = %.2f\n", 2.0 * 3.141592653589793 * value); break;
                default: puts("Invalid operation.");
            }
            break;
        default: puts("Invalid shape.");
    }
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Result = 24.00
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. The outer switch chooses a shape and the inner switch chooses the calculation.
  3. Display the computed result.

The outer switch chooses a shape and the inner switch chooses the calculation.

EFFICIENCY

Time and space complexity

Time complexity

O(1)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.