Need help reversing my output

I'm making a program where i have to convert decimal to octal and binary. They both work except that they print in order, and i want it printed in reverse.

so 125 = 1111101 but i'm getting 1011111.

any ideas? I havent learned arrays so I suppose there is another way of doing it. any help would be appreciated.

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
29
30
31
32
33
34
35
36
37
38
#include "stdafx.h"
#include <iostream>
using namespace std;
const int binary = 2;
const int octal = 8;
const int hexadecimal = 16;
const int mod = 10;

int _tmain(int argc, _TCHAR* argv[])
{
	int decimal=0, remainder=0, integer=0, base=0, digit, newremainder=0, n, mod=0;

	cout<<"Enter a Value: "<<endl; cin>>decimal;
	cout<<"Enter Base for Conversion (2, 8, or 16): "<<endl; cin>>base;
	cout<<" "<<endl;

	while (base == binary && decimal > 0){
		newremainder = decimal;
		newremainder = decimal % binary;
		decimal/=binary;
		cout<<newremainder<<"";
	}

	while (base == octal && decimal > 0){
		newremainder = decimal; 
		newremainder = decimal % octal;
		decimal/=octal;
		
		cout<<newremainder<<"";
	}
	
	cout<<" "<<endl;
	cout<<" "<<endl;
	return 0;
}


	
I'm too beginner and things I say may not be correct. (+My English is terrible)
You need to do it twice, I mean the while loop.
Take a look at this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main()
{
	int a,b=0;
	cin>>a;
	while (a>0)
	{
		b=(b*10)+(a%10);
		a=a/10;
	}
	cout<<b;
}


This code reverses a decimal number, for example:

123456789 will be 987654321 .

Your program is based on this algorithm, so it reverses your number, so you should do it twice:
FirstWay:First reverse number that user enters and then transfer it to the base he wants.
SecondWay:Do your while loop twice, but depends on the base the user wants, you need to calculate the modulo from that number.
In both ways you need to be careful about "ZERO"s, consider that a "0" is the last number of a number, so if you reverse it, it will be first and makes no sense.
(the FirstWay is better and more efficient.)

By the way I think there will be better ways, better ask a professional.
Last edited on
Either you should store a new representation of the number in a container and then reverse its content. Or you can use a recursive function.
There is an example of a recursive function below

1
2
3
4
5
6
void convert( unsigned int x, unsigned int base )
{
   unsigned int digit = x % base;
   if ( x /= base ) convert( x, base );
   std::cout << digit;
}
Last edited on
Topic archived. No new replies allowed.