Search code examples
cif-statementconditional-statementslogical-operatorslogical-and

Logical && operators


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.


Solution

  • 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);
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^