Click here to Skip to main content
15,897,718 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
for(int i=0;i<10;++i){
                System.out.print(i&1);
            }
Posted
Updated 23-Jun-15 23:15pm
v2
Comments
phil.o 24-Jun-15 5:14am    
What is the question?
shivakumar rudroju 24-Jun-15 5:16am    
what does i&1 do ?
phil.o 24-Jun-15 5:28am    
It performs a logical AND between the variable i and the number one.
Logical AND.

OK, I compiled a ran a fixed version of your program for you:
Java
public class Bin
{
  public static void main( String args[])
  {
    for(int i=0;i<10;++i)
    {
      System.out.print(i&1);
    }
  }
}


output:
0101010101


Is it a surprise?
 
Share this answer
 
The & operator in Java is a bitwise AND - which returns zero where any bit in either side of the operator is zero, and one only where the bit in the same position on both sides is one.

So i&1 will return the least significant bit of the number: because you specified the constant 1 - which has only a single bit set, in the least significant position it will ignore all the other bits in the integer, and return a one or zero based solely on the content of the least significant bit.

And since you increase i by one each time you go round the loop, the value of that least significant bit will change from 0 to 1 each time round. You start with zero, and the last time round the loop is with i equal to nine, so you will end with one:
0101010101
 
Share this answer
 
C++

0101010101
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900