How to convert an integer to Roman numerals in C#

1 Answer

0 votes
using System;
using System.Text;

public class IntegerToRoman
{
    public static string IntToRoman(int num) {
        // Define values and their corresponding Roman numerals
        int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        string[] symbols = {
            "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
        };

        var roman = new StringBuilder();

        // Loop through values and subtract while possible
        for (int i = 0; i < values.Length; i++) {
            while (num >= values[i]) {
                num -= values[i];
                roman.Append(symbols[i]);
            }
        }

        return roman.ToString();
    }

    public static void Main(string[] args)
    {
        Console.WriteLine(IntToRoman(1994)); 
        Console.WriteLine(IntToRoman(196)); 
        Console.WriteLine(IntToRoman(9));   
    }
}



/*
run:

MCMXCIV
CXCVI
IX

*/

 



answered Dec 1, 2025 by avibootz
...