Convert decimal to base 2 in C++
Nov 5, 2019 at 10:22am UTC
Hello,
I wrote a program to convert decimal to base 2 in C++ and work fine.
I use Array.
Can I write this program without any data structure or built-in function?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include <iostream>
using namespace std;
int main()
{
{
int num;
cout << "Enter Number \n" ;
cin >> num;
int i = 0;
int base[100];
while (num / 2 !=0 )
{
base[i++] = num % 2;
num /= 2;
}
base[i] = num;
for (int j = i; j >=0 ; j--)
{
cout << base[j];
}
cout << endl;
}
}
Nov 5, 2019 at 10:29am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
using namespace std;
void binary( int num )
{
if ( num >= 2 ) binary( num / 2 );
cout << num % 2;
}
int main()
{
int num;
cout << "Enter number: " ; cin >> num;
binary( num ); cout << '\n' ;
}
Last edited on Nov 5, 2019 at 10:31am UTC
Topic archived. No new replies allowed.