
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ program to Convert a Decimal Number to Binary Number using Stacks
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
#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
- Related Articles
- Java Program to convert binary number to decimal number
- Haskell program to convert a decimal number into a binary number
- C++ Program To Convert Decimal Number to Binary
- Python program to convert decimal to binary number
- Swift program to convert the decimal number to binary using recursion
- Convert decimal to binary number in Python program
- Java program to convert decimal number to binary value
- Java program to convert binary number to decimal value
- C++ Program to Convert Binary Number to Decimal and vice-versa
- Write a Golang program to convert a binary number to its decimal form
- Write a Golang program to convert a decimal number to its binary form
- How to convert a number from Decimal to Binary using recursion in C#?
- Convert decimal fraction to binary number in C++
- Java program to convert decimal number to hexadecimal number
- Java Program to convert hexadecimal number to decimal number

Advertisements