/* ************************************************************************** * Program name : 049_Convert_Decimal_to_any_base(Recursion)(Version 1.00)* * Author : Duck Wong * * Language : C / C++ * * Compiler : Boodshed Dec-C++ compiler Ver 3.95 * * Computer : PII350 * * O/S : Windows 98 * ************************************************************************** * Version 1.00 : 2000/06/30 - first version * ************************************************************************** * Description : (a) Repeat asking an integer number * * (b) Repeat asking convert to base ? * * (c) Output result * * (d) Try again ? * ************************************************************************** */ #include #include char DigitTable[]="0123456789abcdef"; // Note (1) void ConvertBase(int Number, int Base) // Note (2) { if (Number >= Base) ConvertBase(Number / Base, Base); cout << (DigitTable[Number % Base]); } int main() { // part 1 : declaration int Number, Base, Index_1, Index_2; char Again; do { // part 2 : Repeat asking an integer number do { cout << "\n\n\t\tConvert_to_any_base(Recursion Version)\n" << "\n\tPlease input a positive integer number : "; cin >> Number; } while (Number <= 0); // part 3 : Repeat asking convert to base ? do { cout << "\n\tConvert the above number to base : "; cin >> Base; } while (Base<=1 || Base>16 || Base==10); // part 4 : Output result cout << "\n\tThe result is : "; ConvertBase(Number,Base); // part 5 : try another number ? cout << "\n\n\t\aTry another number (Y/N) : "; cin >> Again; cout << "\n"; } while (Again=='Y' || Again=='y'); cout << "\n" << endl; system("PAUSE"); return 0; } /* Notes (1) DigitTable is a string (array of character). (2) Example : Convert 13 (base 10) to base 2 Pass | Number | Number>=Base | Next pass | Output --------------------|---------|--------------|-----------|------- Call 1st pass | 13 | Yes | Yes | Call 2nd pass |13/2 = 6 | Yes | Yes | Call 3rd pass |6/2 = 3 | Yes | Yes | Call 4th pass |3/2 = 1 | No | | 1 Back to 3rd pass |3%2 = 1 | | | 1 Back to 2nd pass |6%2 = 0 | | | 0 Back to 1st pass |13%2 = 1 | | | 1 --------------------|---------|--------------|-----------|------- Therefore the result is : 1101. */