3.1k views

The for loop

for (i=0; i<10; ++i)
printf("%d", i&1);

prints

1. 0101010101
2. 0111111111
3. 0000000000
4. 1111111111
| 3.1k views
0

what the answer would be if it were

printf("%d", i && 1);

Could someone tell why it is happpening so ?

+2
Every operator in C/C++ has a corresponding meaning and result comes from that. "&&" is a logical and operator and all logical operators return either 0 or 1.

Option A is Ans.

Bcz It is Bitwise And Operation.

i      &    1

0000 & 0001=0

0001 & 0001=1

0010 & 0001=0

0011 & 0001=1

Here the result is 1 if LSB of i is 1(Odd no.) & it occur at alternative position

So Ans is 0101010101

http://www.tutorialspoint.com/cprogramming/c_bitwise_operators.htm
by Boss (23.9k points)
edited

(odd no) & 1 = 1

(even no) &1 = 0

Ans- A. 0101010101

by Boss (26.6k points)
Answer is A.the loop runs from 0 to 9 and i&1 MEANS BITWISE AND WITH THE BINARY FORMS OF 0 TO 9 WITH 1.SO THE NUMBERS HAVING LAST BIT AS 0 GIVES OUTPUT 0 AND NUMBERS HAVING LAST BIT AS 1 GIVES OUTPUT 1.
by Active (2.1k points)
Here key point is that for bitwise op to be 1 we must have AND operation of LSB to be 1 here since we have bitwise AND operation performed with 1 whose LSB is 1 therefore all the odd numbers shall have their LSB 's to be 1 so directly we can say that the result of bitwise AND would be 0 for all even numbers and 1 for all odd numbers.so op is option A .
by Loyal (6.4k points)
+1 vote
i&1 is basically checking whether i is even or odd.If it's even it'll return 1 else 0. Based on this I think output should be A.
by (21 points)