In this tutorial, we will write a menu-driven program in C. We will use the switch case statement present in C to create menus or options. Before that, you may go through the following topic in C programming.
C Menu-driven Program using switch case:
This is a menu program in C that displays a menu and takes the input from the user. The choice made by the user is among the option displayed in the menu. And accordingly, the output is displayed on the screen. It is a user-friendly program in C.
Menu Driven Program using Switch Case in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | #include <stdio.h> int main() { int choice; printf("To find the areas of following press:"); printf("\n1 for the Area of a Circle"); printf("\n2 for the Area of a Square"); printf("\n3 for the Area of a Right Angled Triangle"); printf("\n4 for the Area of a Rectangle"); printf("\n5: Area of Rhombus"); printf("\nEnter your Choice: "); scanf("%d", &choice); switch (choice) { case 1: printf("Enter radius for the circle:"); float r, area; scanf("%f", &r); area = 3.14f *r * r; printf("Area: %f", area); break; case 2: printf("Enter side for square:"); int s; scanf("%d", &s); int ae = s * s; printf("Area: %d", ae); break; case 3: printf("Enter height and base for traingle:\n"); float h, bs; scanf("%f", &h); scanf("%f", &bs); float ar = 0.5f *h * bs; printf("Area: %f", ar); break; case 4: printf("Enter length and breadth for rectangle:\n"); int l, b; scanf("%d", &l); scanf("%d", &b); int aa = l * b; printf("Area: %d", aa); break; case 5: printf("Enter the first diagonal of a Rhombus: "); float diagonal1, diagonal2; scanf("%f", &diagonal1); printf("Enter the second diagonal of the Rhombus: "); scanf("%f", &diagonal2); float aRhombus = (diagonal1 *diagonal2) / 2; printf("Area of the Rhombus is: %f", aRhombus); break; default: printf("Invalid Input"); break; } return 0; } |
Output: 1
To find the areas of following press:
1 for the Area of a Circle
2 for the Area of a Square
3 for the Area of a Right Angled Triangle
4 for the Area of a Rectangle
5: Area of Rhombus
Enter your Choice: 1
Enter radius for the circle:2
Area: 12.560000
Output: 2
To find the areas of following press:
1 for the Area of a Circle
2 for the Area of a Square
3 for the Area of a Right Angled Triangle
4 for the Area of a Rectangle
5: Area of Rhombus
Enter your Choice: 4
Enter length and breadth for rectangle:
5
4
Area: 20
Similarly, you can create a calculator or any other program that serves a menu of options to choose from. You can use if..else statement instead of switch case.