Write a program which converts an integer into Roman numerals.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#define N 100

void convertToRoman(int, char *buf);

int main(int argc, char ** argv) {
    int n;
    char buf[N];

    printf("Enter an Integer: ");
    scanf("%d", &n);
    convertToRoman(n, buf);

    printf("%d in roman numerals is %s\n", n, buf);

    return 0;
}


// convertToRoman:
//   In:  val: value to convert.
//        res: buffer to hold result.

void convertToRoman (int val, char *buf) {
    char huns[][5] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
    char tens[][5] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
    char ones[][5] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
    int   size[] = { 0,   1,    2,     3,    2,   1,     2,      3,       4,     2};
    int i = 0, j = 0;
    //  Add 'M' until we drop below 1000.
    char *res = buf;

    while (val >= 1000) {
        *res++ = 'M';
        val -= 1000;
    }

    // Add each of the correct elements, adjusting as we go.

    strcpy (res, huns[val/100]);  res += size[val/100]; val = val % 100;
    strcpy (res, tens[val/10]);   res += size[val/10];  val = val % 10;
    strcpy (res, ones[val]);      res += size[val];

    // Finish string off.

    *res = '\0';
}

When you compile and execute the above program it produces the following result on Linux:

Enter an Integer: 25
25 in roman numerals is XXV

Brief Explanation

  • The function convertToRoman is responsible for converting the integer entered by the user to roman numerals. It takes the number n, and buffer of size 100 as parameters.
  • In function convertToRoman, 2-dimensional arrays huns, tens, ones are declared and initialized with values necessary for our conversion.
  • The integer array 'size' enable us to increment the pointer res appropriately.
  • Since buf was passed to the function by reference, changes made to the array within the function is recognized in the main function hence we can gracefully display the content of the array in our main program as shown using the printf function.

Add comment


Security code
Refresh