Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to convert decimal to binary number

C++ Code Example — Loop Programs

ADVERTISEMENT

WAP to convert decimal to binary number

Objective

Write a C++ program to convert a Decimal number to Binary using Bitwise operators.

Algorithm / Approach

  1. Read a decimal integer n.
  2. Run a for loop starting from 15 down to 0.
  3. Inside the loop, right-shift the bits of n by c positions: k = n >> c.
  4. Use the Bitwise AND operator with 1 (k & 1) to check if the right-most bit is 1 or 0.
  5. Print "1" if true, otherwise print "0".
main.cpp
#include<iostream>
using namespace std;
int main() {
 int n, k, c;
 cout<<"Enter a Number : ";
 cin>>n;
 for(c = 15; c>=0; c--) {
  k = n>>c;
  if(k & 1)
   cout<<"1";
  else
   cout<<"0";
 }
 cout<< endl;
return 0;
}

Expected Output

Enter a Number : 5
0000000000000101

Explanation of the Program

  • Instead of using division and modulo math to calculate the binary representation, this program looks directly at how the computer stores the integer in RAM.
  • The Bitwise Right Shift operator (&gt;&gt;) slides the binary bits of the number to the right. By sliding each bit to the far right position one by one, and using & 1 to inspect it, we can visually print the exact binary memory state of the number.

Complexity

Time Complexity O(1) - Always loops exactly 16 times for a 16-bit visualization.
Space Complexity O(1)
ADVERTISEMENT