C PROGRAMMING PROGRAM • SWITCH & MENU PROGRAMS
Calculate Shape Area Using a switch Menu
Learn how to calculate shape area using a switch menu using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
2 8 5
Sample output
Area = 40.00
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int choice;
double first, second;
printf("1. Circle 2. Rectangle 3. Triangle\nChoose: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter radius: "); scanf("%lf", &first);
printf("Area = %.2f\n", 3.141592653589793 * first * first); break;
case 2:
printf("Enter length and width: "); scanf("%lf %lf", &first, &second);
printf("Area = %.2f\n", first * second); break;
case 3:
printf("Enter base and height: "); scanf("%lf %lf", &first, &second);
printf("Area = %.2f\n", 0.5 * first * second); break;
default: puts("Invalid choice.");
}
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Area = 40.00
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Choose the shape first and then read only the measurements needed by that case.
- Display the computed result.
Choose the shape first and then read only the measurements needed by that case.
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.
