I know I can write this code with fewer lines and I did it before, but I tried with an "if else" chain to explore different ways to code the same program since I'm still learning the basics. But doing this way I can't get the result if the third conditional(C is the greater one) is true. Only if the third conditional is true the program finish without printing anything. What am I doing wrong?
#include <stdio.h>
#include <conio.h>
int main(){
int a, b, c = 0;
printf("Please insert three different numbers:\n");
printf("Insert A value:");
scanf("%d", &a);
printf("Insert B value:");
scanf("%d", &b);
printf("Insert C value:");
scanf("%d", &c);
//comparing A, B and C to find the greater number
if(a > b){
if (a > c){
printf("\nThe greater is A: %d", a);
}
}else if (b > a){
if(b > c){
printf("\nThe greater is B: %d", b);
}
}else{
printf("\nThe greater is C: %d", c);
}
getch();
return 0;
}
CodePudding user response:
Change you if
statements to this:
if(a > b && a > c){
printf("\nThe greater is A: %d", a);
}else if (b > a && b > c){
printf("\nThe greater is B: %d", b);
}else if (c > a && c > b){
printf("\nThe greater is C: %d", c);
}
Also, using the same structure you have, you can use this:
if(a > b){
if (a > c){
printf("\nThe greater is A: %d", a);
}else {
printf("\nThe greater is C: %d", c);
}
}else if (b > a){
if(b > c){
printf("\nThe greater is B: %d", b);
}else{
printf("\nThe greater is C: %d", c);
}