Logical && operators - c

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.

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.

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

#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).

Related

Why no brackets needed among conditions in if sentence?

int num;
scanf("%d", &num);
if (num % 4 == 0 && num%100 != 0 || num % 400 == 0)
printf("%d", 1);
else
printf("%d", 0);
In this logic, I found I do not need to do () in AND condition which is in front of OR condition.
if (*(num % 4 == 0 && num%100 != 0)* || num % 400 == 0)
It's only needed if (num % 4 == 0 && num%100 != 0 || num % 400 == 0) without () in front of OR condition.
so, it seems (A && B || C) works like ((A && B) || C)
but it seemed it could work as (A && (B || C)) condition.
Why is () not needed in this situation? A and B condition are automatically grouped from the beginning?
All operators in C (and in fact all languages) have what's called operator precedence which dictates which operands are grouped first.
The logical AND operator && has a higher precedence than the logical OR operator ||, which means that this:
A && B || C
Is the same as this:
(A && B) || C
So if you want B || C to be grouped together, you need to explicitly add parenthesis, i.e.:
A && (B || C)
Parentheses decide order of operations, if you move the parentheses around you may change what the output is. In the same way that (A + B) / C is different from A + (B / C) but still a valid equation.
See Order of Operations in C
Logical AND has higher priority than OR:
https://en.cppreference.com/w/c/language/operator_precedence
dg

behavior of print function inside a Boolean expression [duplicate]

This question already has answers here:
What is short circuiting and how is it used when programming in Java? [duplicate]
(5 answers)
Closed 2 years ago.
language: C
a bool expression outputs 0 if 0 is entered, else 1 will be the output.
following the above statement,
CASE 1:
input
#include <stdio.h>
#include <stdbool.h>
main()
{
int a = 1,
b = 2;
bool res = ((a == b) && ("your "));
printf("res = %d", res);
}
output
res = 0
CASE 2:
input
bool res = (!(a == b) && ("your "));
printf("res = %d", res);
output
res = 1
CASE 3:
now i add prinf function to ("your ")
input
bool res = ((a == b) && printf("your "));
printf("res = %d", res);
output
res = 0 //adding printf doesn't change the output
CASE 4:
input
bool res = (!(a == b) && printf("your "));
printf("res = %d", res);
output
your res = 1 // i expected just "res = 1" not "your res = 1"
how is the print function not executed in CASE 3 but executed in CASE 4?
According to the C Standard (6.5.13 Logical AND operator)
4 Unlike the bitwise binary & operator, the && operator guarantees
left-to-right evaluation; if the second operand is evaluated, there is
a sequence point between the evaluations of the first and second
operands. If the first operand compares equal to 0, the second
operand is not evaluated.
In the expression used as an initializer in this declaration
bool res = ((a == b) && printf("your "));
the first operand (a == b) of the logical AND operator evaluates to 0. So the second operand that is the call of printf is not evaluated,
On the other hand, in this expression used as an initializer in the declaration
bool res = (!(a == b) && printf("your "));
the first operand !(a == b) evaluates to 1. So the second operand that is the call of printf is also evaluated.
The evaluation of logical and operator && is short-circuit evaluation.
Considering A && B, firstly A is evaluated. When A is true, A && B can become true and B is evaluated. When A is false, A && B will never be true and B is not evaluated.
Now look at actual cases.
In CASE 3 (a == b) && printf("your "), (a == b) is false because a (1) is not equal to b (2). Therefore now we lost all chance for the expression (a == b) && printf("your ") to become true and therefore printf("your ") is not evaluated. This means the function is not executed.
In CASE 4 !(a == b) && printf("your "), !(a == b) is true because (a == b) is false. Now the expression !(a == b) && printf("your ") may become true depending on the value of printf("your "), so printf("your ") is evaluated and the function is executed.
In Case 3:
It is due to compiler optimizing the statement. The statement is translated and evaluated from left to right because of the usage of parentheses. The first expression is: (a == b) is false because of the values of a and b. The compiler figured out that the result of the expression in ((a == b) && printf("your")) will always yield false. So optimization dictates not to generate code for printf("your").
I bet if you compile this in demode mode, you will see the expected result.
Explanation of case 4 is left for yourself. It is obvious. (hint pay attention to the precedence of the operators "!", "&&")
Good luck.

Regarding if else statements in C language

Please explain to me why this code is wrong for the task and below I have explained all the four conditions -[][1]
#include stdio.h
int main()
{
int n;
scanf ("%d", &n); //taking input
if (n / 2 != 0)
{
printf ("Weird"); //checking first condition
}
else if (n % 2 == 0 && 2 <= n <= 5)
{ //checking second condition
printf ("Not Weird");
}
else if (n % 2 == 0 && 6 <= n <= 20)
{ //checking third condition
printf ("Weird");
}
else if (n % 2 == 0 && n > 20)
{ //checking fourth condition
printf ("Not Weird");
}
else
{
printf ("Error");
}
return 0;
}
this is the image for the question[1]: https://i.stack.imgur.com/OtY7o.png**
Testing for Odd or Even
n / 2 != 0 does not test whether n is odd. n/2 calculates the quotient that results from dividing n by 2 (rounding any fraction down). So 0/2 is 0, 1/2 is 0, 2/2 is 1, 3/2 is 1, 4/2 is 2, and so on. So n / 2 != 0 is true for all n other than −1, 0, and 1.
To test whether a number is odd, you can use n % 2 != 0. n%2 calculates the remainder from the division. If it is zero, n is even. If n is not zero, n is odd.
Using Else Efficiently
Once you have tested whether n is odd using n % 2 != 0, you do not have to test whether it is even in the else clauses. The else expressions and their statements will be evaluated only if the if expression is false, which happens (after the correction above) only when n is even. So we do not need to test again.
Testing For an Interval
In C, 2 <= n <= 5 does not test whether n is between 2 and 5. It is parsed as (2 <= n) <= 5. This is evaluated by comparing 2 to n, which produces 0 (if false) or 1 (if true). This result, 0 or 1, is then used in … <= 5. Since 0 and 1 are both less than or equal to 5, the result is always 1 (for true).
To test whether n is greater than or equal to 2 and less than or equal to 5, you must write this out explicitly: 2 <= n and n <= 5, which we join with the “and” operator, &&: 2 <= n && n <= 5.
Other Issues
The proper form for including stdio.h is #include <stdio.h>, not #include stdio.h.
A proper declaration for main is int main(void), not int main().
Corrected Program
A program with these issues corrected is:
#include <stdio.h>
int main(void)
{
int n;
scanf("%d", &n); //taking input
if (n % 2 != 0)
{
printf ("Weird"); //checking first condition
}
else if (2 <= n && n <= 5)
{ //checking second condition
printf ("Not Weird");
}
else if (6 <= n && n <= 20)
{ //checking third condition
printf ("Weird");
}
else if (n > 20)
{ //checking fourth condition
printf ("Not Weird");
}
else
{
printf ("Error");
}
return 0;
}
There is a typo in the line:
if (n / 2 != 0)
The compiler will not complain, but you will get unexpected results at run time.
Here you meant to check if the remainder of division by 2 is not equal to zero (i.e.: modulus operator), and not the division by 2. This line should be
if (n % 2 != 0)
Second thing: you can't tell C to compare values in ranges like this 2 >= n >= 4. You will have to split the comparison into 2 comparisons. This line:
else if (n % 2 == 0 && 2 <= n <= 5)
Should be:
else if (n % 2 == 0 && 2 <= n && n <= 5)
You will need to fix all the lines that have this comparison as well.

scanf does not ask for input

It takes a lot of time to compile, and some random number shows up, apparently the scanf() doesn't ask for the input
#include <stdio.h>
int main() {
int a;
//a = 1472464;
scanf ("%d", &a);
if ((a % 6) && (a %4) == 0)
{
printf("Input %d is divisible by 6 and 4\n", a);
}
else {
printf(" Input %d is not divisible by 6 and 4\n", a);
}
printf("Hello, World!\n");
return 0;
}
This line is wrong:
if ((a % 6) && (a %4) == 0)
It should be:
if ((a % 6) == 0 && (a %4) == 0)
I don't see any other obvious problem with the code.
The expression (a % 6) && (a %4) == 0 does not compare both modulo-operations with zero. Instead it does (a % 6) which will result on a number between 0 and 5, and use that as a boolean value that it then uses with the result of (a %4) == 0.
Instead you need to do each comparison separately: (a % 6) == 0 && (a % 4) == 0
The important thing to know here is that in C only zero and a null pointer is considered "false". Anything that is not zero (or a null pointer) is true.
That means that if a for example is 4 then a % 6 will be "true" since a % 6 is 4 which is not zero. Conversely when a is for example 6 then a % 6 will be 0 which is "false".
So using only a % 6 will actually give the opposite result to what you want, it will be "true" when a is not evenly dividable by 6.

How to write a while statement in c?

I should write a C while statement that continues while x is both larger than 10 and a multiple of either 6 or 7. I only need to include the actual while statement, not the entire loop!
I know it may look funny to you, but this is what I have so far.
#include<stdio.h>
int main(){
int x;
while (x > 10, x % 7 = 0 || x % 6 = 0) {
printf("%d\n", x);
}
}
Logical and is &&. As an operator, , is "ignore the result of the thing to the left".
Your Boolean logic and comparison both use the wrong syntax. It should be like this:
while (x > 10 && (x % 7 == 0 || x % 6 == 0)) {
The comma (,) is not a valid Boolean operator. What you wanted is && (logical AND). You need parentheses around the other two expressions because AND (&&) has higher precedence than OR (||).
And = is for setting values; == is for comparing them.
Finally, as others pointed out, you don't set x anywhere in the code that you have posted. So, your loop will not run. And you don't modify x in the loop, so, if you ever get into the loop, you will never get out.
The program can look like
#include <stdio.h>
int main( void )
{
int x;
printf( "Enter an integer number: " );
scanf( "%d", &x );
while ( x > 10 && ( x % 7 == 0 || x % 6 == 0 ) )
{
printf( "%d\n", x );
printf( "Enter next integer number: " );
scanf( "%d", &x );
}
}
Or you could enlarge the condition in the while loop the following way (to check that the input is correct)
#include <stdio.h>
int main( void )
{
int x;
printf( "Enter an integer number: " );
while ( scanf( "%d", &x ) == 1 && x > 10 && ( x % 7 == 0 || x % 6 == 0 ) )
{
printf( "%d\n", x );
printf( "Enter next integer number: " );
}
}
As for your condition in the while loop then it has two errors
while (x > 10, x % 7 = 0 || x % 6 = 0)
It uses the comma operator instead of logical operator && and it uses the assignment operator as for example x % 7 = 0 instead of the comparison operator x % 7 == 0. Also variable x was not initialized.
Your while statement should read
while (x > 10 && (x % 7 == 0 || x % 6 == 0))
Note the use of && for "boolean and", and == for "equality comparison".
I should Write a C while statement that continues while x is both
larger than 10 and a multiple of either 6 or 7. I Only need to include
the actual while statement, not the entire loop!
Let's analyze the condition that will go in the while() statement:
x is both larger than 10 and a multiple of either 6 or 7
Can be expressed as
x is greater than 10 AND a multiple of 6 OR multiple of 7
So let's code that in C:
x is greater than 10
x>10
AND
&&
x multiple of 6 OR x multiple of 7
(x%6)==0 || (x%7)==0
Then, all together
x>10 && ( (x%6)==0 || (x%7)==0 )
So your while sentence is like this:
while (x>10 && ( (x%6)==0 || (x%7)==0 ))
{
stuff...
}
Here can be the Solution Ava
while (x > 10 && (x % 7 == 0 || x % 6 == 0)) {

Resources