Recursion: I've spent hours and mission failed. A program that ask user to enter a number and a base to be converted. Example, number 31, base 16, answer is 1f. Im stuck on recursive case and the problem with storing int to char array
char(or string?) convert (int num, int base, char ans[]) { .......//need help here convert(num/base,base,ans); ......//need help here }
A question, mate: does it need to be recursive? If not, I think the code will be very much simplified. If yes, then consider the example for base 16 conversion, like: http://codepad.org/vcwc1kZP
(By the way, that's not my code. I found it at http://www.dreamincode.net/forums/topic/152630-problem-with-converting-decimal-number-to-hexadecimal-number/ )
This function will work with integers, and looks good for any base. It just needs a main() written for it. #include <stdio.h> #include <stdlib.h> int mkDigit( int number, int base, char* answer ) { char characters[] = { "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" }; int remainder, index; if( number == 0 ) return( 0 ); remainder = number % base; number /= base; index = mkDigit( number, base, answer ); answer[ index ] = characters[ remainder ]; return( ++index ); }
Join our real-time social learning platform and learn together with your friends!