The Gateway to Computer Science Excellence
+8 votes
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
in Programming by Veteran (106k points) | 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.

5 Answers

+18 votes
Best answer
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 by
+7 votes

(odd no) & 1 = 1

(even no) &1 = 0

Ans- A. 0101010101

by Boss (26.6k points)
+3 votes
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)
+3 votes
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)
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,737 questions
57,391 answers
198,591 comments
105,442 users