2

I have a functionality where user will be prompted to choose one of the three options.

1. for insert
2. for delete
0. for quit

I have a infinite for loop which will continuously ask user to do something. If user choose 0, I want the infinite loop to break. I cannot figure out how to break a for loop inside switch case.

for(;;){
        printf("please enter :\n");
        printf("1 for INSERT\n");
        printf("2 for DELETE\n");
        printf("0 for quit\n");
        
        printf("what's your value ?\n");
        scanf("%d",&operation);
        switch(operation){
            case 1:
                 printf("you choose to INSERT. Please inter a value to insert\n");
                 scanf("%d",&value);
                 insertAtBeginning(value);
                 break;
            case 2:
                 printf("you choose to DELETE\n");
                 
                 deleteFromBeginning();
                 break;
            case 0:
                  break;
        }
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
AL-zami
  • 8,902
  • 15
  • 71
  • 130
  • For just three options, may as well use and `if/else if/else` chain; the switch gains you nothing, and blocks `break` from working. Of course, `goto` to a label just below the `for` loop is an option here as well. – ShadowRanger Mar 06 '16 at 03:44

4 Answers4

2

Instead of an infinite for loop, you can use a while loop and check the value of operation instead and leave out the 0 case:

operation = -1;              // initialize
while (operation != 0) {     // check operation instead
    printf("please enter :\n");
    printf(" 1 for INSERT\n");
    printf("2 for DELETE\n");
    printf("0 for quit\n");

    printf("what's your value ?\n");
    scanf("%d",&operation);
    switch(operation){
        case 1:
             printf("you choose to INSERT. Please inter a value to insert\n");
             scanf("%d",&value);
             insertAtBeginning(value);
             break;
        case 2:
             printf("you choose to DELETE\n");

             deleteFromBeginning();
             break;
    }
}
dbush
  • 205,898
  • 23
  • 218
  • 273
1

maybe u can try while(selection != 0) instead of infinite for loop

Jones Joseph
  • 4,703
  • 3
  • 22
  • 40
1

Use a flag to decide when to break.

bool end = false;

for(;!end;) {
    switch(operation) {
        case 0:
            end = true;
            break;
    }
}
Alex P
  • 5,942
  • 2
  • 23
  • 30
0

You can achieve it by putting a if condition for you condition 0 and put break. if (your-condition==0) break; The meaning behind break in switch statement doesn't mean exit from for loop, it just exit from switch case.