How Program works?
Lets take an example of 11.
Now divide it by 2 and note down the remainder.
So. 11 / 2 , Remainder = 1.
Quotient: 5 / 2 , Remainder = 1.
Quotient: 2/2 , Remainder = 0.
Quotient: 1/2, Remainder = 1.
Now Quotient = 0. Stop.
Binary number is the Remainders in reverse order i.e. Binary of 11 = 1011
PROGRAM:
#include<iostream>
using namespace std;
void binary(int num)
{
int rem;
if (num <= 1)
{
cout << num;
return;
}
rem = num % 2;
binary(num / 2);
cout << rem;
}
int main()
{
int dec, bin;
cout << "Enter the number : ";
cin >> dec;
if (dec < 0)
cout << dec << " is not a positive integer." << endl;
else
{
cout << "The binary form of " << dec << " is ";
binary(dec);
cout << endl;
}
return 0;
}