# Converting integer to roman numeral in C++

In this tutorial, we are going to learn about converting an integer into its corresponding roman numeral. We will use C++ for this task. Roman numerals are something which we are familiar with since primary schools and we see them everywhere especially on clocks. Now, before deep-diving let us have a quick look over roman numerical.

Roman numerals are a numeral system that originated in ancient Rome. Roman numbers are represented by combinations of letters from the Latin alphabet. There are seven symbols each with a fixed value as given below,

```I - 1
V - 5
X - 10
L - 50
C - 100
D - 500
M - 1000```

Fact – Since after 1000 there is no symbol for 10000, the highest roman numeral that we can write is 3999.

Roman numerals are formed by the combination of the above seven symbols. Now that we know about roman numbers let us jump right to the code implementation.

## C++ Code to convert integer to roman numeral

Below is our given C++ program to perform the task:

```#include <iostream>
#include <bits/stdc++.h>
using namespace std;
string ToRoman(int A) {
map<int,string>m;
m = "I";
m = "II";
m = "III";
m = "IV";
m = "V";
m = "VI";
m = "VII";
m = "VIII";
m = "IX";
m = "X";
m = "XX";
m = "XXX";
m = "XL";
m = "L";
m = "LX";
m = "LXX";
m = "LXXX";
m = "XC";
m = "C";
m = "CC";
m = "CCC";
m = "CD";
m = "D";
m = "DC";
m = "DCC";
m = "DCCC";
m = "CM";
m = "M";
m = "MM";
m = "MMM";
string ans="";
int j = 1;
while(A>0){
j = j*10;
int k = A%(j);
ans = m[k] + ans;
A = A-k;
}
return ans;

}

int main()
{
int a = 246;
string s = ToRoman(a);
cout << a <<" in roman numeral is "<<s;
return 0;
}
```

Output –

`246 in roman numeral is CCXLVI`

Let us take a quick look at the above code.

As mentioned in the problem we have an integer and we try to convert it to its corresponding roman numeral. At first, we create a map in which we put the numbers 0-9, 10, 20, 30, 40, .. 90, 100, 200, 300,… 900, 1000, 2000, 3000. We do this because as soon as we know how to write the above numbers in roman then essentially can write each and every number into its roman for.
After creating a map we run a while loop. Upon having a careful look at the while loop we see that at every iteration single digit of the number is processed (starting from unit digit to highest digit). We take the corresponding roman value from the map and append it to our answer.

For example for integer = 246
At first, we process 6 thus ans = VI and our integer becomes 240.
Second, we process 40 thus ans  = XLVI and the integer become 200.
Third, we process 200 and ans = CCXLVI and our loop terminates.

Hope you understood the code! Thank You.

Check out my other blogs-
Knuth-Morris-Pratt (KMP) Algorithm in C++
Stock Span Problem in C++