In: Computer Science
C++ program
Write a recursive function that converts Old Roman Numeral to base 10 values. Print out the Old Roman Number and it base 10 equivalents. You will read all the digits of a Roman number into an array of characters. You will process each Roman digit in the array using ONLY POINTERS. Putting a ‘\0’ at the end of the input characters allows you to print the string easier.
Use the following input to test your function: DVIII, MMMDCCCCLXXXXIIII, DCLXVI, CCCLXXXVII
//without using map,
#include
using namespace std;
int character_used(char r)
{
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return -1;
}
int mainFunctionworking(string& myArray)
{
// initialize sum to zero
int sum = 0;
// Traverse given input
for (int i = 0; i < myArray.length(); i++) {
// Getting character_used of symbol s[i]
int s1 = character_used(myArray[i]);
if (i + 1 < myArray.length()) {
// Getting character_used of symbol s[i+1]
int s2 = character_used(myArray[i + 1]);
// Comparing both character_used
if (s1 >= s2) {
// character_used of current symbol
// is greater or equal to
// the next symbol
sum = sum + s1;
}
else {
// character_used of current symbol is
// less than the next symbol
sum = sum + s2 - s1;
i++;
}
}
else {
sum = sum + s1;
}
}
return sum;
}
// Driver Program
int main()
{
// Considering inputs given are valid
string myArray = "DVIII";
cout << "Decimal equivalent for "<<myArray<<" is "<< mainFunctionworking(myArray) << endl;
myArray = "MMMDCCCCLXXXXIIII";
cout << "Decimal equivalent for "<<myArray<<" is "<< mainFunctionworking(myArray) << endl;
myArray = "DCLXVI";
cout << "Decimal equivalent for "<<myArray<<" is "<< mainFunctionworking(myArray) << endl;
myArray = "CCCLXXXVII";
cout << "Decimal equivalent for "<<myArray<<" is "<< mainFunctionworking(myArray) << endl;
return 0;
}