I would like to have two nested menus in my program but it keeps looping both menus, after I entered the option for the second menu. When I remove the first menu, the code is working fine.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a, b, c, d, choice1, choice2, i, s[100], swap;
unsigned long int fact;
while(1)
{
printf("Menu Driven Program\n");
printf("1. 2D Array\n");
printf("2. Exit\n");
printf("Enter your choice\n");
scanf("%d", &choice1);
switch (choice1)
{
case 1:
printf("Choose options given below\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Linear search\n");
printf("5. Bubble sort\n");
printf("6. Exit\n");
printf("Enter Your Choice\n\n");
scanf("%d", &choice2);
break;
switch (choice2)
{
case 1:
printf("Enter any two numbers\n");
scanf("%d%d", &a, &b);
c = a b;
printf("Your answer is %d \n", c);
break;
}
}
}
}
the output will be
Menu Driven Program
1. 2D Array
2. Exit
Enter your choice
1
Choose options given below
1. Addition
2. Subtraction
3. Multiplication
Menu Driven Program
1. 2D Array
2. Exit
It is stuck in the loop where it goes back to the beginning after I entered the value for the second menu. I would like it to enter the case
of the second switch so that it runs the addition code.
CodePudding user response:
From what I can understand, the switch(choice2)
should be executed after choice1
was set to 1
. If that is the case, you need to remove the break
after the scanf
like so:
while(1) {
printf("Menu Driven Program\n");
printf("1. 2D Array\n");
printf("2. Exit\n");
printf("Enter your choice\n");
scanf("%d", &choice1);
switch (choice1) {
case 1:
printf("Choose options given below\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Linear search\n");
printf("5. Bubble sort\n");
printf("6. Exit\n");
printf("Enter Your Choice\n\n");
scanf("%d", &choice2);
switch (choice2) {
case 1:
printf("Enter any two numbers\n");
scanf("%d%d", &a, &b);
c = a b;
printf("Your answer is %d \n", c);
break;
}
break; // Break here important otherwise fall-through to exit()-call
case 2:
exit(EXIT_SUCCESS);
}
}