I tried to write an easy program that compares 3 numbers and prints the biggest of them but it keeps printing all 3 of them and I don\'t get why. That\'s my code:
You have a semicolon after your if
condition:
if((x > y) && (x > z));
The semicolon takes the place of the block or statement to be executed when the condition is true. It's as if you had written:
if((x > y) && (x > z))
{
;
}
{
printf("%d",x);
}
You can hopefully see how this will execute the print statement unconditionally.
Remove the semicolon at the end of each if statement. That is causing the if statement to run the null statement (;) and then subsequently run a block statement { printf(...); }
#include <stdio.h>
int main()
{
int x = 10;
int y = 8;
int z = 3;
if((x > y) && (x > z))
{
printf("%d",x);
}
if((y > x) && (y > z))
{
printf("%d",y);
}
if((z > x) && (z > y))
{
printf("%d",z);
}
return 0;
}
The logic is simplier if you use an additional variable for maximum
#include <stdio.h>
int main()
{
int x,y,z, max;
scanf ("%d", &x);
max = x;
scanf ("%d", &y);
if (y > max)
max = y;
scanf ("%d", &z);
if (z > max)
max = z;
printf ("max = %d", max);
return 0;
}
The answer to your question is purely based on the knowledge of using semicolon in C and syntax of if
statement.
For more information read semicolon and have a clear understanding ofif
syntax.
You should use else , you should remove the semi-colons after the if statements , the semi colons after ifs means that the body of the if is empty and the other stuff is a normal block of code
#include <stdio.h>
int main()
{
int x = 10;
int y = 8;
int z = 3;
if((x > y) && (x > z))
{
printf("%d",x);
}
else { // Will not make difference in this particular case as your conditions cannot overlap
if((y > x) && (y > z))
{
printf("%d",y);
}
else { // Will not make difference in this particular case as your conditions cannot overlap
if((z > x) && (z > y))
{
printf("%d",z);
}
}
}
return 0;
}