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.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
1 2 6
Sample output
Result = 24.00
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Result = 24.00
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- The outer switch chooses a shape and the inner switch chooses the calculation.
- 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.
