Turn Switch statement into if/then and if/else statement

4187 views c
2

I want to make this switch statement into if/else and if/then statement. My Switch statement is :

char option;
printf("Choose your option : ");
scanf("%c",&option);

switch(option){
    case 'a':
    case 'A': a = 20 + 10 ;
        printf("Addition process result:%d",a);
        break;
    case 'b':
    case 'B': a = 20 - 10 ;
        printf("Subtraction process result:%d",a);
        break;
    case 'c':
    case 'C': a = 20 * 10 ;
        printf("Multiplication process result:%d",a);
        break;
    case 'd':
    case 'D': a = 20 + 10 ;
        printf("Division process result:%d",a);
        break;
    default:
        printf("Invalid option");
    }

answered question

I won't answer, because I think your code works better with a switch statement.

Make an attempt. If you can't get it working, show us what you've tried.

1 Answer

11

You just do:

if(option == 'a' || option == 'A') {
    // do whatever
}
else if (option == 'b' || option == 'B') {
    // do whatever
}

... the other else if's

then for the "invalid option", you have just an else {}. If the first if or any of the subsequent if else's evaluate true, then all the others will be skipped.

posted this

Have an answer?

JD

Please login first before posting an answer.