简体   繁体   中英

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

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");
    }

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 else if's evaluate true, then all the others will be skipped.

like this:

#include <stdio.h>

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

    if (option == 'a' || option == 'A') {
        int a = 20 + 10;
        printf("Addition process result:%d", a);
    } else if (option == 'b' || option == 'A') {
        int a = 20 - 10;
        printf("Subtraction process result:%d", a);
    } else if (option == 'c' || option == 'C') {
        int a = 20 * 10;
        printf("Multiplication process result:%d", a);
    } else if (option == 'd' || option == 'D') {
        int a = 20 + 10;
        printf("Division process result:%d", a);
    } else {
        printf("Invalid option");
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM