singlepiece000
singlepiece000

Reputation: 37

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

Upvotes: 0

Views: 77

Answers (2)

Austin Stephens
Austin Stephens

Reputation: 401

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.

Upvotes: 1

Yunbin Liu
Yunbin Liu

Reputation: 1498

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

Upvotes: 1

Related Questions