Why no brackets needed among conditions in if sentence? - c

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

Related

Why does this following program print "Yes" instead of "No"?

Why does this following program print "Yes" instead of "No"?
None of the variables is initialized to 2.
bool hello = 0;
int a = 1;
int b = 3;
int c = 4;
int d = 5;
if (a || b || c || d == 2) {
hello = 1;
}
if (hello == 1) {
printf("Yes");
}
if (hello == 0) {
printf("No");
}
return 0;
}
The statement
if (a || b || c || d == 2)
is equivalent to:
if (a != 0 || b != 0 || c != 0 || d == 2)
The equality comparison does not automatically distribute across all the variables. If you want to do that, you need to perform all the comparisons explicitly:
if (a == 2 || b == 2 || c ==2 || d == 2)
The expression (a || b || c || d == 2) evalutates to true because it treats a, b, c as booleans, and any non-zero integer is true.
You have given logical operator in the expression It means that if non zero value came then the expression is true. Then hello=1 is set and in next f statement it prints YES
You just meet the short circuit behavior of logical expressions OR.
The order of evaluation of logical OR || is left to right.
So in the following expression:
left || right
if left = true then right will never going to be executed (short circuit). In your code exactly same happened.
As you know, any non zero value treated as true in C, hence, a which is 1 is true. So, take a look:
if (a || b || c || d == 2)
if (true || bla bla bla) //rights are not even checked!
if (true)
hello = 1;
Tada! So the program print "Yes"!
None of the variables is initialized to 2.
Yes of course! But your if condition is not going to check that. To do so, try this:
if (a == 2 || b == 2 || c ==2 || d == 2) {
//...
because if judge num is not zero , if think this is true. so your code
if (a || b || c || d == 2)
like
if ( true || true || true || false)
the result is true, programe print "YES"

If statement for structure

I have to write if statement for structure for person which:
Is older or equal 16 and younger or equal 20
First letter of name and surname must be 's' or 'n'
My code:
if(x.name[0]=='s' ||
x.name[0]=='n' &&
x.surname[0]=='s' ||
x.surname[0]=='n' &&
(x.age>=16 && x.age<=20))
{
/* print person */
}
I want just to print out these persons, but code prints non-compliant ages.
What is wrong with the condition?
Enclose each || section in brackets. Keep in mind && has higher priority than ||. Like so:
if((x.name[0]=='s' || x.name[0]=='n') &&
(x.surname[0]=='s' || x.surname[0]=='n') &&
(x.age>=16 && x.age<=20))
Splitting the code on several lines is not needed it just makes the code more readable.
This should work:
(x.name[0]=='s' || x.name[0]=='n') && (x.surname[0]=='s' || x.surname[0]=='n') && (x.age>=16 && x.age<=20)
Additional pair of () added. Also, You know that such a cumbersome statements are considered to be a really bad practice?
Your missing parenthesis around the name and surname conditions
if((x.name[0]=='s' || x.name[0]=='n') && (x.surname[0]=='s' || x.surname[0]=='n') && (x.age>=16 && x.age<=20))
On seeing the statement
if(x.name[0]=='s' ||
x.name[0]=='n' &&
x.surname[0]=='s' ||
x.surname[0]=='n' &&
(x.age>=16 && x.age<=20))
compiler interpret it as
if(x.name[0]=='s' || (x.name[0]=='n' && x.surname[0]=='s') ||
(x.surname[0]=='n' && x.age>=16) && x.age<=20))
The reason behind this is, logical operator && has higher precedence than that of logical || operator. What does it mean then?
It means that the expression (sub-expression) get bound more closely to && than that of ||.
Take a small example to understand this
#include <stdio.h>
int main(void)
{
int i = 1, j = 1, k = 1;
printf("%d ", i++ || ++j && ++k);
printf("%d %d %d", i, j, k);
return 0;
}
The output of this program is:
1
2 1 1
On first look a novice may think that the output is wrong and it should be
1
2 1 2
by thinking that i++ || ++j && ++k is same as (i++ || ++j) && ++k but this is not true. Because of the higher precedence of && over ||, sub-expressions j++ and k++ bound to && and it will be interpreted by the compiler as i++ || (++j && ++k)

C while loop logic ( y != ( 1 || 0) )

I have the below code to choose sin or cos to be integrated,
while( x !=1 || y !=(1||0) ){
printf("Sin (1) or Cos (0)?\n");
x = scanf("%d",&y);
_flushall();
if(y==1){
printf("Sin set\n");
}
else if(y==0){
printf("Cos set\n");
}
}
However the
y!= (1||0)
never evaluates to true for y == 0 , can someone explain what's wrong here? Thanks.
You need (y != 1 && y != 0) (or similar, it depends on what you really mean to express there). The || operator is being applied to the operands 1 and 0. Put another way, y != (1 || 0) means "Do (1 || 0) then do y != result".
You are attempting to effectively code directly Boolean algebra, and C doesn't accept it in the manner you've provided.
while( x !=1 || y !=(1||0) )
should be
while( (x!=1) || ( (y!=1) || (y!=0) ) )
Never underestimate the value of using excess parentheses in C. The optimizer will likely optimize the code to be more efficient anyways.
The part of code that generates this error evaluates as follows:
LHS (left hand side), RHS (right hand side)
LHS = y
!= (1||0) [definition given]
!= (1) [b/c (1||0) = (1)]
y != (0||1)
is equivalent to
y != 1
since 0||1 is 1. You'll need two comparisons if you want y != 0 or y != 1.

HCL three input odd parity

I have three inputs: a,b, and c. If my output is 1 then there are odd number of inputs with 1. Otherwise it is 0.
I have tried so far (a && b && c) || (!a && !b && !c), (a && b && c) || (!a && b && c), (a && c) || (b&& !c) and quite a few others. How can I do this?
How about a ^ b ^ c?
If only basic logic operators are allowed, you can use this
((a && b || !c) || (!a && !b || !c)) && (!a || !b || c) && (a || b || c)
as dbaupp commented, just equivalent transformation.

Operator precedence and ternary operator

I have a problem in C.
#include<stdio.h>
int main()
{
int a = 10, b = 0, c = 7;
if (a ? b : c == 0)
printf("1");
else if (c = c || a && b)
printf("2");
return 0;
}
This code prints 2 but I think a?b:c returns b=0 and 0==0 returns 1. Can you explain the code?
The conditional operator (?:) has one of the lowest precedences. In particular it is lower than ==. Your statement means this:
if(a ? b : (c == 0)) { ... }
Not this:
if((a ? b : c) == 0) { ... }
Your conditions are not properly written.
In the first if-statement:
if (a ? b : c == 0)
if you put the values, then it becomes
if(10 ? 0 : 7 == 0)
means, it will always return 0.
That's why control goes to the else part and there, it becomes
else if (7 = 7 || 10 && 0)
since you used the "=" operator here (c = c), it will be always true, therefore it prints "2".
Now you want that code should return "1", then change your if statement in this way.
if( (a ? b:c) == 0){...}
because "==" operator has higher precedence than ternary operator.

Resources