Print out all odd number from 1 to 100 using a for loop!

The very first thought likely to hit will be that of taking mod 2(%2) of numbers from 1 to 100 in a loop and checking whether it yield an remainder or not. But there is even better a way to deal with it.

                 for( unsigned int i = 1; i < = 100; i++ )
                        if( i & 0×00000001 )
                                 cout << i<<” “;

The catch is, only odd number’s binary representation ends with ‘1’.Check the below table

Dec Hex Bin
000 00 00000000
001 01 00000001
002 02 00000010
003 03 00000011
004 04 00000100
005 05 00000101
006 06 00000110
007 07 00000111
008 08 00001000
009 09 00001001
010 0A 00001010
011 0B 00001011
012 0C 00001100
013 0D 00001101
014 0E 00001110
015 0F 00001111

6 Responses to “Print out all odd number from 1 to 100 using a for loop!”


  1. 1 Shanil July 20, 2007 at 9:13 am

    Gud technique!!!

  2. 2 mohanraj September 24, 2007 at 12:47 pm

    do you have someother methods

  3. 3 Vineeth December 31, 2007 at 12:52 pm

    Good :)

  4. 4 Hash January 21, 2008 at 10:33 pm

    What was meant by the statement :
    “The catch is, only prime number’s binary representation ends with ‘1’”

    9 is not a prime. However it also ends in ‘1′
    “009 09 00001001″

    Or did you mean something else?

  5. 5 Gov January 22, 2008 at 9:29 am

    It was a typo,I have corrected it

  6. 6 Chris Buckley June 30, 2008 at 4:01 pm

    How about

    for (unsigned int i = 1; i <= 100; i += 2)
    cout << i << ” “;

Leave a Reply




 

July 2007
S M T W T F S
« Jun   Aug »
1234567
891011121314
15161718192021
22232425262728
293031  

Categories

Blog Stats

  • 29,660 hits

Last 100 Visitors

Map IP Address

Map IP Address