C Programming - Structures, Unions, Enums - Discussion

Discussion Forum : Structures, Unions, Enums - Find Output of Program (Q.No. 7)
7.
What will be the output of the program ?
#include<stdio.h>

int main()
{
    int i=4, j=8;
    printf("%d, %d, %d\n", i|j&j|i, i|j&j|i, i^j);
    return 0;
}
12, 12, 12
112, 1, 12
32, 1, 12
-64, 1, 12
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
58 comments Page 1 of 6.

Laxman said:   7 years ago
In function data passing, expressions are evaluated from right to left,but printing results from left to right, so in the given problem first (i^j) evaluated,

i=0100
j=1000
i^j=1100 equivalent decimal is 12.

Then, next expression is (i|j&j|i)
the expression having bitwise AND and OR, in this bitwise AND having higher priority than bit wise OR, so grouping made as i|(j&j)|i, in this first (j&j) evaluated.

j=1000
j=1000
j&j=1000.

The remaining expression made as i|(1000)|i; here bitwise OR having two times that means same priority now we have to consider associativity. For bitwise operators left to right.

i=0100
1000
res=1100
1000

Final res=1100 decimal value 12.
third also same as the second expression so the result is 12.

Now printing the results in 12 12 12.
(12)

Vedhashree said:   1 decade ago
i= 4 =>0100 ; j=8 =>1000
solution for : i|j&j|i

& ->AND has highest Precedence than | ->OR operator hence should be evaluated first and then from left to right as usual .


So Step 1: 0100 | (1000 & 1000) | 0100
becomes 0100 | 1000 | 0100
Step 2: (0100 | 1000) | 0100
becomes 1100 | 0100
Step 3: (1100 | 0100)
becomes 1100 which is equivalent to 12


Solution for i ^ j

Step 1: 0100 ^ 1000
becomes 1100 which is equivalent to 12

Hence the answer 12,12,12
(4)

Vasantha said:   10 years ago
4 value in binary is: 0100.

8 value in binary is: 1000.

4|8 = 0100|1000 = 1100 (According to the truth table of AND).

8|4 = 1000|0100 = 1100 (According to the truth table of OR).

12 value in binary is: 1100.

12 & 12 = 1100 & 1100 = 1100.

And 4^8 = 0100^1000 = 1100 = 12 (According to the truth table of XOR).
(2)

Umesh Pandey said:   9 years ago
Tricky method.

i|j&j|i, i|j&j|i gives same value.

The option is only 12,12 ie A.
(1)

Ravi said:   7 years ago
Good explanation, Thanks. @Ramadas.
(1)

Parth said:   1 decade ago
The first two have to be same and there is only one matching option to that, so common sense if not logic.

Sonali said:   9 years ago
Good explanation @Abinandank.

Mindmaster said:   9 years ago
Operators of same precedence are executed from left to right.

Shakshi said:   9 years ago
Thanks, @Vadhashree. it's a clear explanation.

Sushant said:   9 years ago
@Kavi.

& is a bitwise operator.

Whereas;

&& is a logical operator.


Post your comments here:

Your comments will be displayed after verification.