Print numbers having first and last bits as the only set bits

CServer Side ProgrammingProgramming

The task is to print the given n number which have exactly two set bits that neither less than 2 nor more than 2.

Set bits in computer language are the one that have value 1 and unset bits have value as 0

Input: value of num=5
Output: 1 3 5
   As 1 is equivalent to 1 in binary
      3 is equivalent to 11 in binary
      5 is equivalent to 101 in binary


Step 1 -> declare variable as unsigned int num=5 and int i=1
Step 2 -> print i
Step 3 -> Loop For i=3 and i<=num and ++i
   IF (!(i-1 & i-2))
      Print i


#include <stdio.h>
int main(int argc, char const *argv[]) {
   unsigned int num = 5;
   int i = 1;
   printf("%d ", i); //printing first number 1
   for (i = 3; i <= num; ++i) {
      if(!(i-1 & i-2)) //performing and operation on i-1 and i-2
      printf("%d ", i);
   return 0;


if we run the above program then it will generate the following output

1 3 5
Updated on 30-Jul-2019 22:30:26