// ex_ch9_9.c -- generalized binary.c
#include <stdio.h>

void to_base_n(unsigned long n, int base);

int main(void)
{
	unsigned long number;
	int base;
	
	printf("Enter an integer (q to quit): ");
	while (scanf("%ul", &number) == 1)
	{
		printf("Convert to which base (2-10): ");
		
		/* this is somehow broken as it locks up when 11 is entered
		   twice or 1 is entered twice */
		while ((scanf("%d", &base) != 1) || (base < 1 || base > 10))
		{
			printf("Convert to which base (2-10): ");
			scanf("%*s");
		}
		
		printf("Base-%d equivalent: ", base);
		to_base_n(number, base);
		putchar('\n');
		printf("Enter an integer (q to quit): ");
	}
	printf("Done.\n");
	return 0;
}

void to_base_n(unsigned long n, int base)
{
	int r;
	
	r = n % base;
	if (n >= base)
		to_base_n(n / base, base);
	printf("%d", r);
	
	return;
}
