Maximum of two numbers by switch case code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Maximum of two numbers by switch case code

Can someone please help me with a code to get a maximum of two numbers using a switch case code. I have been trying today and ended up using the following ; switch (number1 >number2) case 1: //codes case 0: //codes Although it runs it keeps warning me that the switch condition contains boolean value

7th Feb 2020, 3:08 PM
Kaiza Ilomo
Kaiza Ilomo - avatar
8 Answers
+ 2
Hm. You can always explicitly convert it: (int)(n1>n2) That should normally get rid of the warning.
7th Feb 2020, 3:45 PM
HonFu
HonFu - avatar
+ 1
HonFu these last two solutions worked. Thanks
7th Feb 2020, 4:47 PM
Kaiza Ilomo
Kaiza Ilomo - avatar
0
Did you really do this in C and not in C++? I don't get a boolean warning, and I also didn't expect one either, since in C such an expression should be converted to 1 or 0 simply. Maybe you should show us the actual code (this one wouldn't even run as it is written).
7th Feb 2020, 3:23 PM
HonFu
HonFu - avatar
0
I did this in C en the actual... the warning is given by the compiler
7th Feb 2020, 3:41 PM
Kaiza Ilomo
Kaiza Ilomo - avatar
0
Actual code.. int main (void) {int num1, num2; printf ("Enter two numbers:") ; scanf ("%d%d", &num1, &num2) ; if (num1!=num2) {switch (num1 >num2) {case 1: printf ("%d is greater than %d. \n", num1, num2); break ; case 0: printf ("%d is greater than %d.", num2, num1) ; break;} } else printf ("%d is equal to %d.", num1, num2) ; return 0; }
7th Feb 2020, 3:52 PM
Kaiza Ilomo
Kaiza Ilomo - avatar
0
Converting switch (int) (num1 >num2) does not work Sorry it worked I wrote switch (int) (num1>num2) instead of switch ((int) num1 >num2)
7th Feb 2020, 4:09 PM
Kaiza Ilomo
Kaiza Ilomo - avatar
0
When I have a problem like this, I try a minimalistic code snippet that expresses the shape I'm struggling with. switch(3>4) { case 1: printf("yep"); break; case 0: printf("nope"); break; } If I run this here, it runs without problems. And if I run this: switch((int)3>4) { case 1: printf("yep"); break; case 0: printf("nope"); break; } It still works. Can you try these in your environment and see if it works?
7th Feb 2020, 4:35 PM
HonFu
HonFu - avatar
0
import java.util.Scanner; class Switch{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("enter a integer"); int a=sc.nextInt(); System.out.println("enter a integer"); int b=sc.nextInt(); int c=(a>b)?1:0; switch(c) { case 1: System.out.println("a is greater"); break; case 0: System.out.println("b is greater"); break; default: System.out.println("invalid"); break; } } }
21st Mar 2024, 3:05 PM
Mamathareddy Kunta
Mamathareddy Kunta - avatar