Problem Statement:
Write a function to find the binary equivalent of a given
decimal integer and display it.
decimal integer and display it.
Solution:
//Ahmad Furqan
//P5.h
#include <iostream>
#include <conio.h>
using namespace std;
void num2bin(int num)
{
bool bin[25];
int i = 0;
for (i = 0; i < 25; i++)
{
bin[i] = num % 2; //divide number by 2 successively and save remainders
if (num < 2)
break;
num /= 2;
}
for (i; i >= 0; i--)
{
cout << bin[i]; //show remainders in reverse order
}
}
void main(void)
{
int num;
cout << "Enter a number: ";
cin >> num;
cout << "The binary equivalent of this number is: ";
num2bin(num);
_getch();
}
No comments:
Post a Comment