#include <stdio.h>
#include <math.h>
/* converts to binary */
int main()
{
unsigned int decimalNUM = 0;
printf("Enter a number to be converted to binary.\t");
scanf("%d", &decimalNUM);
fflush(stdin);
baseConv(decimalNUM);
getchar();
return 0;
}
baseConv(unsigned int n){
if (n == 0) ;
while (n > 0){
printf("%d", n%2);
n = n >> 1;
}
return 0;
}
I know how to do this now, but it prints backwards. How would I go about reversing it?
If you want a way to reverse an operation like this, one way is to use a stack data structure.
Instead of printing the values in your main loop, push them on to the stack.
Then, once you're finished that, pop an item off the stack and print it, then keep doing that until the stack is empty. A stack is known as a LIFO structure (last-in, first out) and is a handy way of storing things for later retrieval in the opposite order they were generated.
Pseudo-code:
def baseConv (n):
create stack s
while n > 0:
push n % 2 onto s
n = n >> 1
while not empty(s):
pop n from s
print n
I should also add that the statement:
if (n == 0);
doesn't really do anything useful at all.