Home > other >  How to do 2 main menu without looping
How to do 2 main menu without looping

Time:04-03

I wanna do 2 main menu but it keep looping in second menu anyone know what's wrong? but when i remove first menu the code 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 keep looping. i want it to do addition but cannot

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); 
    }
}
  •  Tags:  
  • c
  • Related