C++ Program to Convert Decimal to Binary

Conversion Between Binary and Decimal

C++ programs to convert decimal to binary have been shown here. Both the iterative and recursive approaches have been covered.






1. C++ Program to convert decimal to binary

Code has been copied
/****************************************
	   alphabetacoder.com
C++ program to convert decimal to binary
*****************************************/

#include <iostream>

using namespace std;

int main() {
    // declare variables
    long num;
    int bin[31] = {0};
    int i, n = 0;

    // take input
    cout << "Enter the number in decimal: ";
    cin >> num;

    // convert the number in binary
    //store the result in an array
    // binary number would be stored
    // in reverse order 
    while (num > 0) {
        bin[n] = num % 2;
        n++;
        num = num / 2;
    }

    // display the number in binary
    cout << "Binary: ";
    for (i = n - 1; i >= 0; i--) {
        cout << bin[i];
    }

    // new line
    cout << endl;

    return 0;
}

Output


Enter the number in decimal: 93

Binary: 1011101





2. C++ Program to convert decimal to binary using recursion

Code has been copied
/******************************
	alphabetacoder.com
C++ program to convert decimal 
to binary using recursion
*******************************/

#include <iostream>

using namespace std;

// recursive function to display  
// decimal to binary
void decimal_to_binary(long num) {
    if (num > 1) {
        // call the function
        decimal_to_binary(num / 2);
    }
    // display binary digit
    cout << (num % 2);
}

int main() {
    // declare variables
    long num;

    // take input
    cout << "Enter the number in decimal: ";
    cin >> num;

    cout << "Binary: ";
    // call function to display 
    // the decimal number in binary
    // display the number in binary
    decimal_to_binary(num);

    // new line
    cout << endl;

    return 0;
}

Output


Enter the number in decimal: 17

Binary: 10001