Decimal to Binary in C++
Posted by Samath
Last Updated: December 26, 2014

Write a program that prompts the user to enter a decimal integer and displays its corresponding binary value. 

Solution:

#include <iostream>
#include <cstdlib>
 
using namespace std;
void binary(int);
 
int main(int argc, char *argv[])
{
	int num;

	cout << "Enter a decimal number: ";
	cin >> num;
	
	cout<<num;
	cout<<" in decimal system is equal to ";
	binary(num);cout<<" in binary system.\n\n";
}

void binary(int num) 
{
	int remainder;

	if(num <= 1) 
	{
		cout << num;
		return;
	}

	remainder = num%2;
	binary(num >> 1);
	    
	cout << remainder;
}