Home » C Programs » Menu Driven Program in C

Menu Driven Program in C

In a software with a menu structure, the user is presented with a list of options (the menu) and prompted to choose one. The driver then invokes the proper function to carry out the action chosen by the menu item. It seems logical to handle the menu choices using a switch statement.

Switch Statement in C

A switch statement enables the comparison of a variable’s value to a list of possible values. Each value is referred to as a case, and each switch case checks the variable being turned on. Any number of case instances may be included in the switch statement. However, within a single switch statement, no two constant-expression values may have the same value. The first statement in or after the corresponding labeled-statement is where the switch statement body is executed.

Break Keyword in Switch

The do, for, switch, or while statement that is immediately around the break statement is terminated. The statement that follows the ended statement receives control.

#include <stdio.h>
void
main ()
{
  
int num1, num2, opt;
printf ("Enter the Number A");
scanf ("%d", &num1);
printf ("Enter the Number B");
scanf ("%d", &num2);
printf ("\nEnter Your Options\n");
printf
    ("1-Add\n2-Substract\n3-Multiply\n4-Division\n5-Exit\n");
scanf ("%d", &opt);
switch (opt)    {
case 1:
printf ("The Add of  %d and %d is %d\n", num1, num2, num1 + num2);
break;
case 2:
printf ("The Substract of %d & %d is %d\n", num1, num2,num1 - num2);
break;
case 3:
printf ("The Multiply of %d & %d is %d\n", num1, num2,num1 * num2);
break;
case 4:
if (num2 == 0)
	{
printf ("The Second Number is Zero and Divide by Zero\n");
}
      else
	{
printf ("The Division of %d & %d is  %d\n", num1, num2,num1 / num2);
}
break;
case 5:
break;
default:
printf ("Enter Correct Options\n");
break;
}
}


Output:

Enter Your Options
1-Add
2-Substract
3-Multiply
4-Division
5-Exit
1
The Add of 450 and 450 is 900