Home > front end >  How I do this in switch statement
How I do this in switch statement

Time:03-13

Convert the following codes into switch statement:

int a = 5, b = 10, c = 15, choice;
choice = a > b && a>c ? a: (b > c ? b: c);
printf(“%d”, choice);

I try this way.

#include<stdio.h>
int main()
{
    int a = 5, b = 10, c = 15, choice;
    switch(choice)
    {
       case 'a > b && a>c':
       {
           choice=a;
           break;
       }
       case 'b > c':
       {
           choice=b;
           break;
       }
       default :
       {
           choice=c;
           break;
       }    
    }
    printf("%d",choice);    
}

but its output always come C. If I give a=15,b=10,c=5 output comes out 5 wheres it should be 15. Where I did wrong??

CodePudding user response:

You want largest of (a, b, c) to be the choice. switch(logical-condition) evaluates to either true or false.

It's not recommended to use switch in this scenario. However, for the learning angle:

#include <stdbool.h> // for true/false flags

    switch (a > b) {
    case true :
        switch (a > c) {
        case true:
            choice = a;
            break;
        case false:
            choice = c;
            //break;    //redundant
        }
        break;
    case false:
        switch (b > c) {
        case true:
            choice = b;
            break;
        case false :
            choice = c;
            //break;    //redundant
        }
        //break;    //redundant
    }
  • Related