Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How I do this in switch statement

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??

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading