Reputation: 23
if ((a % 5) && (a % 11))
printf("The number %d is divisible by 5 and 11\n", a);
else
printf("%d number is not divisible by 5 and 11\n", a);
How will the logical &&
operator work if I don't add == 0
in the expression, if there is no remainder, will it look for the quotient? and the quotient will always be a non zero term so the programme will always return true.
Upvotes: 1
Views: 124
Reputation: 310910
According to the C Standard (6.5.13 Logical AND operator)
3 The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.
In the expression used in the if statement
if ((a % 5) && (a % 11))
if each operand a % 5
and a % 11
is unequal to 0 then the expression evaluates to logical true. That is when a
is not divisible by 5
and is not divisible by 11
then the expression evaluates to true and as a result a wrong message is outputted in this statement
printf("The number %d is divisible by 5 and 11\n", a);
To make the output correct you should change the expression in the if statement the following way. Pay attention to that you need also to change the message in the second call of printf.
if ((a % 5 == 0) && (a % 11 == 0 ))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
printf("The number %d is divisible by 5 and 11\n", a);
else
printf("%d number is either not divisible by 5 or by 11\n", a);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Upvotes: 2
Reputation: 7726
@Saurav's answer best describes about your problem. In addition to it, if you want a solution in case you are not in mood to add == 0
, then you could just simply use !
(NOT) operator:
if (!(a % 5) && !(a % 11))
Now it will show divisible
only when both of the expression has zero values (i.e. no remainder - like the number 55
).
Upvotes: 0
Reputation: 134286
In your code
if ((a % 5) && (a % 11))
is the same as
if ( ((a % 5) != 0) && ((a % 11) != 0 ) )
Any non-zero value is taken as TRUTHY.
Upvotes: 3