Exercise:
Write a C++ program that can display decimal numbers as binary numbers and binary numbers as decimal numbers.
1. Decimal to Binary
Click Here to View the Solution:
#include <iostream>
#include <cmath>
using namespace std;
long long DecimalToBinary(int);
int main()
{
int num, ans;
cout << "Insert any decimal number to be converted: ";
cin >> num;
ans = DecimalToBinary(num);
cout << num << " is " << ans << " in Binary" << endl ;
return 0;
}
long long DecimalToBinary(int num)
{
long long ans = 0;
int y,x = 1;
while (num!=0)
{
y = num%2;
num /= 2;
ans += y*x;
x *= 10;
}
return ans;
}
Click Here to View the Output:
Insert any decimal number to be converted: 364 364 is 101101100 in Binary
Click Here to View the Explanation:
- This function uses recursion
DecimalToBinary ()
. num
is divided by 2 and the remainder is stored asy
.num
is assigned a new value bynum = num/2
.ans
is also assigned a new value:ans = ans + y*x
x
is assigned a new value:x = x*10
- If the remainder of
num
when divided by 2 is 0, x will also be equal to 0. - The answer is printed on screen.
2. binary numbers as decimal numbers
Click Here to View the Solution:
#include <iostream>
#include <cmath>
using namespace std;
int BinaryToDecimal(long long);
int main()
{
long long num;
cout << "Insert any binary number to be converted: ";
cin >> num;
cout << num << " is " << BinaryToDecimal(num) << " in Decimal";
return 0;
}
int BinaryToDecimal(long long num)
{
int ans = 0, x = 0, Rem;
while (num!=0)
{
Rem = num%10;
num /= 10;
ans += Rem*pow(2,x);
++x;
}
return ans;
}
Click Here to View the Output:
Insert any binary number to be converted: 101101100 101101100 is 364 in Decimal
Click Here to View the Explanation:
- This function also uses recursion.
- A number is taken from the user
num
. - Through recursion,
num
is divided by 10 and the remainder is stored in a variableRem
. - To find the
ans
,ans = ans + Rem*pow(2,x)
. Remainder is multiplied by 2 poweredx
, and added toans
. - The value of
x
is incremented by 1 through every iteration.