The subject for this month is a program to convert Arabic numbers into Roman numerals. These numbers appear often in our society: on buildings, in books, on statues, etc. They are often used where a date is to be represented in a fashion that will last for hundreds of years. Have you ever thought how you might "teach" a computer to print out the year, or any year, in Roman numerals?
The program consists of a number of parts. The basic program is a text mode 32-bit application that runs in a "Command Box" (sometimes called a DOS box). As such, it is generally computer and compiler independent. I will be using the Microsoft C++ compiler but it should run on GNU or other compilers. When the program starts it announces itself and asks for a number. It then uses several routines to convert the number into Roman. For example, if you enter 1957, it prints out MCMLVII.
The program demonstrates some of the basic parts of the C and C++ language including: functions, string conversions, character arrays, recursion, standard input and output, and text display.
int main(int argc, char* argv[]) { char buff[50]; unsigned int n ; /* Number to be converted */ int code; printf("\n\n ROMAN NUMERAL CONVERSION UTILITY ( end = 0 )\n"); do { printf("\n Enter a number, 0..65535 : "); fgets(buff,50,stdin); code=sscanf(buff,"%5u",&n); if (code != 1) continue; /* go to top of loop */ result[0] = 0; /* erase previous result */ convert(n); printf( "%5u -----------------------------> %s\n",n,result); if(n > 3999) printf("( Special characters: * 5000, # 10000, @ 50000 )\n"); } while (n > 0); return 0; } void convert(unsigned int n) /* Convert the number to R.N. */ { /* NON-Recursive version */ char buff[20]; int i, len; sprintf(buff,"%u",n); len = strlen(buff); for (i=0; i < len; i++) { tentimes(); /* Multiply result string by 10 */ roman(buff[i] - '0'); /* fill 'result' buffer */ } } void convert2(unsigned int n) /* Convert the number to R.N. */ { /* Recursive version */ if (n/10 != 0) { convert2(n / 10); /* R e c u r s i v e c a l l */ tentimes(); /* Multiply result string by 10 */ } roman(n % 10); /* Convert this one digit */ }