How to can I use switch statement in this code? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 1

How to can I use switch statement in this code?

/* A function that reads four arguments and returns the greatest of them.*/ #include <stdio.h> int max_of_four(int a, int b, int c, int d) { if(a>b && a>c && a>d) { // I want to add a switch statement here insted of if/else if. How can I do it so? return (a); } else if (b>a && b>c && b>d) { return (b); } else if (c>a && c>b && c>d) { return (c); } else { return (d); } } int main() { int a, b, c, d; scanf("%d %d %d %d", &a, &b, &c, &d); int ans = max_of_four(a, b, c, d); printf("%d", ans); return 0; }

8th Nov 2021, 1:45 PM
šŸ‘‘š•¾š–†š–Žš–‹ š•¾š–š–†š–š–—š–Žš–†š–—šŸ‘ØšŸ»ā€šŸ’»[8UG HUNT3R]šŸŽ–ļø
šŸ‘‘š•¾š–†š–Žš–‹ š•¾š–š–†š–š–—š–Žš–†š–—šŸ‘ØšŸ»ā€šŸ’»[8UG HUNT3R]šŸŽ–ļø - avatar
1 Resposta
+ 4
A switch works with a expression that must be integral or enumerates type. Then compares that to a constant expression. switch(expression){ case constant-expression: statement(s); break; .... case default: statement(s); If you need to use switch: int max_of_four(int a, int b, int c, int d){ Int max = 1; If(b >= max) max = 2; If(c >= max) max = 3; If(d >= max); max = 4; switch(max){ case 1: return a; case 2: return b; ... } } It would probably be simpler to put. your integers into an array then sort them and return index 0.
8th Nov 2021, 2:50 PM
William Owens
William Owens - avatar