How to convert an integer to Roman numerals in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

void intToRoman(int num, char *roman) {
    // Define values and their corresponding Roman numerals
    int values[]   = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    const char *symbols[] = {
        "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
    };

    roman[0] = '\0'; // start with empty string

    for (int i = 0; i < sizeof(values)/sizeof(values[0]); i++) {
        while (num >= values[i]) {
            num -= values[i];
            strcat(roman, symbols[i]); // append symbol
        }
    }
}

int main(void) {
    char roman[64]; // buffer for result

    intToRoman(1994, roman);
    printf("%s\n", roman); 

    intToRoman(196, roman);
    printf("%s\n", roman);

    intToRoman(9, roman);
    printf("%s\n", roman); 

    return 0;
}



/*
run:

MCMXCIV
CXCVI
IX

*/

 



answered Apr 23, 2025 by avibootz
edited Dec 1, 2025 by avibootz
...