C++ program to Convert a Decimal Number to Binary Number using Stacks

C++Server Side ProgrammingProgramming

In this problem, we will see how to convert a decimal number to binary numbers using stacks. As we know that the decimal numbers can be converted using binary after dividing it by 2 and taking the remainder. We take the remainder from last to first, so we can easily use the stack data structure to do that.

Input: Decimal number 13
Output: Binary number 1101

Algorithm

Step 1: Take a number in decimal
Step 2: while the number is greater than 0:
Step 2.1: Push the remainder after dividing the number by 2 into stack.
Step 2.2: set the number as number / 2.
Step 3: Pop elements from stack and print the binary number

Example Code

 Live Demo

#include<iostream>
#include<stack>
using namespace std;
void dec_to_bin(int number) {
   stack<int> stk;
   while(number > 0) {
      int rem = number % 2; //take remainder
      number = number / 2;
      stk.push(rem);
   }
   while(!stk.empty()) {
      int item;
      item = stk.top();
      stk.pop();
      cout << item;
   }
}
main() {
   int num;
   cout << "Enter a number: ";
   cin >> num;
   dec_to_bin(num);
}

Output

Enter a number: 18
10010
raja
Published on 28-Mar-2019 16:52:03
Advertisements