The function saves the remainder of the division of the number with 2, calls the same function with the quotient generated after division, the number is printed after the number drops to less than equal to one and then the stack created due to recursion is unwind and the number are printed.
Here is source code of the C++ program which converts decimal to binary value. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
* C++ Program to Convert Decimal to Binary Value
using namespace std;
void binary(int num)
if (num <= 1)
cout << num;
rem = num % 2;
binary(num / 2);
cout << rem;
int dec, bin;
cout << "Enter the number : ";
cin >> dec;
if (dec < 0)
cout << dec << " is not a positive integer." << endl;
cout << "The binary form of " << dec << " is ";
cout << endl;
$ g++ main.cpp $ ./a.out Enter the number : 10 The binary form of 10 is 1010
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
If you liked this C++ Program, kindly share, recommend or like below!