user10591439
user10591439

Reputation:

Choose an option with switch-case and go back to menu (C)

I have this code for example :

   void example()  {
   int i,j,k;
   int sum = 0;
   int a;
   printf("Menu");
   printf("Enter 1 for first case or 0 to exit");
   scanf("%d" , &a);

switch(a){
    case 1:
        printf("first case");
        printf("now go back to Menu");
        break;}

case 0:
    exit(0);

    break;}

I would like to know if i choose the first case how i can go every time back to :

printf("Menu"); 

I dont want to call the example() function, i just want to go in this specific line.

Can i do this with switch-case statement or with something else?

Upvotes: 0

Views: 1317

Answers (1)

Use a loop:

while(1) {
   printf("Menu");
   printf("Enter 1 for first case or 0 to exit");
   scanf("%d" , &a);

   switch(a){
    case 1:
        printf("first case");
        printf("now go back to Menu");
        break;

    case 0:
        exit(0);
    }

    default:
        break;
}

Side notes:

  1. You should add a default mark, when a is neither 1 or 0.

  2. If you want the illusion of different screens you also need to clear the current screen with f.e. printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");.

  3. If the only input is 1 or 0, if/else would be more appropriate than a switch statement.

For example:

while(1) {
   printf("Menu");
   printf("Enter 1 for first case or 0 to exit");
   scanf("%d" , &a);

   if(a == 1) {
        printf("first case");
        printf("now go back to Menu");
        break;
    }
    else if(a == 0) {
        exit(0);
    }

    printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}

Or even simpler:

while(1) {
   printf("Menu");
   printf("Enter 1 for first case or 0 to exit");
   scanf("%d" , &a);

   if(a == 0) {
        exit(0);
    }

    printf("first case");
    printf("now go back to Menu");

    printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}

Upvotes: 2

Related Questions