Some code I don't understand.

I was reading through C++ interview questions to quiz myself and look for new concepts to research and I found this question:

"Write a short code using C++ to print out all odd number from 1 to 100 using a for loop."

The answer was:

1
2
3
for( unsigned int i = 1; i < = 100; i++ )
if( i & 0x00000001 )
cout << i << \",\";  


The middle line makes no sense to me and I was wondering if someone could explain it. Thanks.
if( i & 0x00000001 ) is the equivalent to (i & 1).

'0x00000001' is the hex representation of 1 and '&' is the bit-wise 'AND' operator which is usually used for bit manipulation. i & 0x00000001 will mask off all of the other digits except for the last one. If the last bit is a one then it is odd.
I rather think it's the last line that makes no sense. \",\" ?

The middle line evaluates to true if the least significant bit is set, which is true of any odd number and not true of any even number.

binary numbers:

binary     decimal
1          1
10         2
11         3
100        4
101        5
110        6
111        7
1000       8


See a pattern there?
Consider the binary representations of the integers.
0 0000
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 1001
etc.

Notice the right-most column alternates between 0 and 1. Odd numbers end with a 1, even numbers end with a 0.

The bitwise and operator & is used to isolate just that last digit, it thus allows a simple test for odd or even numbers.

However, I would have done this:
1
2
for (unsigned int i = 1; i <= 100; i += 2 )
    cout << i << " "; 
There are two ways to check whether a number is even or odd. The first one is to consider the remainder of the division by 2. For example

if ( x % 2 != 0 ) std::cout << x << " is odd\n";
else std::cout << x << " is even\n";

And the second one is consider the least significant bit in the binary representation of a number. To extract this bit you can use bit-wise operator & (AND)

For example

if ( x & 1 ) std::cout << x << " is odd\n";
else std::cout << x << " is even\n";

In the code you showed it would be simpler to write

if ( i & 1 )

insetad of

if( i & 0x00000001 )

because it is not necessary that an object of type int occupies exactly 4 bytes on different platforms.
Last edited on
Topic archived. No new replies allowed.