C++ Program to Convert Roman Numeral to Decimal Number

Problem:

Write a C++ program to implement a class 'RomanNumeral' which stores the Roman Numeral as a string. Define a member function to get corresponding decimal value of entered roman numeral. The decimal values of roman numerals are as follows, M 1000, D 500, C 100, L 50, X 10, V 5, I 1. Write a main function to illustrate the use of this class.

Algorithm or Solution:

  1. Start
  2. Declare Roman variable to represent roman number as object of the class string.
  3. Write accept and display functions to get and display the roman numeral.
  4. Define a function called dec() which returns the decimal value of single alphabet of Roman string.
  5. Define a function called getDecimal() to return decimal value of Roman string.
  6. In this function initialize integer variable decimal=0.
  7. In getDecimal() read the string from start i.e from 0 index.
  8. Store the decimal values of first two characters of the Roman string in two temporary variables tmp1 and tmp2 using the dec() function.
  9. If tmp1 is greater than or equal to tmp2 then add tmp1 in the decimal variable, else subtract tmp1 from the decimal variable.
  10. Return the decimal variable.
  11. Write a main function to use 'RomanNumeral' class.
  12. End

C++ Program:


/* Aim: Write a class to implement RomanNumerals and a function to get corresponding decimal value. */

#include<iostream>
using namespace std;

class RomanNumeral
{
	string Roman;

	public:
 
	void setter(string rom)
	{
		Roman=rom; 
	}

	void getter()
	{
	cout<<Roman;
	}


	int dec(char ch)
	{
		switch(ch)
		{
		case 'M':
		case 'm':
		return 1000;

		case 'D':
		case 'd':
		return 500;

		case 'C':
		case 'c':
		return 100;

		case 'L':
		case 'l':
		return 50;

		case 'X':
		case 'x':
		return 10;

		case 'V':
		case 'v':
		return 5;

		case 'I':
		case 'i':
		return 1;
		}
	}

	int getDecimal()
	{
		long int decimal=0;
		int i,tmp1,tmp2;

		for(i=0;Roman[i]!='\0';i++)
		{
			tmp1=dec(Roman[i]);
			tmp2=dec(Roman[i+1]);
   
			if(tmp1>=tmp2)
			{
			decimal+=tmp1;
			}
			else
			{
			decimal-=tmp1;
			}
		}

		return decimal;
	}

};

int main()
{
	RomanNumeral R;
	string rom;
	long int dec;

	cout<<"\n Enter any roman numeral:- ";
	cin>>rom; 
	R.setter(rom);
	dec=R.getDecimal();

	cout<<"\n Decimal equivalent is ";
	cout<<dec<<endl;

	return 0;
}


/* Output of above code:-

 Enter any roman numeral:- MCXIV

 Decimal equivalent is 1114

*/