Convert Decimal to Binary

Decimal to Binary Conversion in C++ (5 Programs)

IntermediateTopic: Advanced Number Programs
Back

C++ Convert Decimal to Binary Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int decimal;
    long long binary = 0;
    int remainder, i = 1;
    
    cout << "Enter a decimal number: ";
    cin >> decimal;
    
    int temp = decimal;
    
    while (temp != 0) {
        remainder = temp % 2;
        temp /= 2;
        binary += remainder * i;
        i *= 10;
    }
    
    cout << "Decimal: " << decimal << " = Binary: " << binary << endl;
    
    return 0;
}
Output
Enter a decimal number: 10
Decimal: 10 = Binary: 1010

Understanding Convert Decimal to Binary

This program converts decimal to binary by repeatedly dividing by 2 and collecting remainders. It demonstrates 5 different methods: using while loop, using recursion, using bitset, using string, and using bit manipulation.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents