Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Convert a given integer to a roman numeral

C++ Math: Exercise-18 with Solution

Write a C++ program to convert a given integer to a roman numeral.

From Wikipedia:
Roman numerals are a numeral system that originated in ancient Rome and remained the usual way of writing numbers throughout Europe well into the Late Middle Ages. Numbers in this system are represented by combinations of letters from the Latin alphabet. Modern usage employs seven symbols, each with a fixed integer value:[1]
CPP Math exercises: Convert a given integer to a roman numeral

Sample Input: n = 7
Sample Output: Roman VII

Sample Input: n = 19
Sample Output: Roman XIX

Sample Solution:

C++ Code :

#include <iostream>
  
using namespace std; 

    string integer_to_Roman(int n) {

        string str_romans[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

        string result = "";

        for (auto int i = 0; i < 13; ++i)
        {
            while(n - values[i] >= 0)
            {
                result += str_romans[i];
                n -= values[i];
            }
        }

        return result;
    }

  
int main()  
{  
    int n = 7;
	cout << "Integer " << n << " : Roman " << integer_to_Roman(7) << endl;
	n = 19;
	cout << "Integer " << n << " : Roman " << integer_to_Roman(19) << endl;
	n = 789;
	cout << "Integer " << n << " : Roman " << integer_to_Roman(789) << endl;
	n = 1099;
	cout << "Integer " << n << " : Roman " << integer_to_Roman(1099) << endl;
	n = 23456;
	cout << "Integer " << n << " : Roman " << integer_to_Roman(23456) << endl;			
    return 0;  
}  

Sample Output:

Integer 7 : Roman VII
Integer 19 : Roman XIX
Integer 789 : Roman DCCLXXXIX
Integer 1099 : Roman MXCIX
Integer 23456 : Roman MMMMMMMMMMMMMMMMMMMMMMMCDLVI

Flowchart:

Flowchart: Convert a given integer to a roman numeral

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to multiply two integers without using multiplication, division, bitwise operators, and loops.
Next: Write a C++ program to convert a given roman numeral to a integer.

What is the difficulty level of this exercise?