Program : convert decimal number to binary

Pls. help me to write a program to convert a decimal number to its equivalent binary number.
BINARY OF 11 IS 1011 BUT I GOT IT IN REVERSE ORDER ie:1101
How can I solve this problem
Last edited on
THANK YOU FOR YOUR REPLY
BINARY OF 11 is 1011 BUT I GOT IT IN REVERSE ORDER ie:1101
How can I solve this problem
it is result of conversion logic -> when you're converting, you write the result starting from LSB (least significant bit), while when you are storing your converted number into array (or whatever you doing there), you are starting from array[0]

That's why you are getting i.e. 1011 from 13 instead of 1101...

If you stored your conversion result in array, just reverse the elements inside, i.e.
1
2
for(int i = array.lenght - 1; i >= 0; i--)
        cout<<result[i];


if you don't like it, you can convert your number using recursion, like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//...
void convert(int a)
{
	if(a > 0)
	{
		convert(a / 2);
		cout << (a % 2);
	}
}
int main()
{
	int number;
	cout << "Insert decimal number: ";
	cin >> number;
	convert(number);
	cin.sync();
	cin.get();
	return 0;
}
THANK YOU Sir the code is working. But I didn't got the use of cin.sync() and cin.get() statements
in the main().
Topic archived. No new replies allowed.