In: Computer Science
Write a program in C++ that converts a positive integer into the Roman number system. The Roman number system has digits
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
Numbers are formed according to the following rules. (1) Only numbers up to 3,999 are represented. (2) As in the decimal system, the thousands, hundreds, tens, and ones are expressed separately. (3) The numbers 1 to 9 are expressed as
I 1
II 2
III 3
IV 4
V 5
VI 6
VII 7
VIII 8
IX 9
As you can see, an I preceding a V or X is subtracted from the value, and you can never have more than three I’s in a row. (4) Tens and hundreds are done the same way, except that the letters X, L, C and C, D, M are used instead of I and V, X, respectively.
Can this be done in C++ without arrays
SOLUTION-
I have solve the problem in C++ code with comments and screenshot
for easy understanding :)
CODE-
#include <iostream>
using namespace std;
int main()
{
// declare a integer variable number
int number;
// Ask user to enter the number until the number is valid(1 -
3999)
do {
cout << "Enter a number between 1 and 3999: ";
cin >> number;
}while(number < 1 || number > 3999);
// Initialize an array of string which stores the roman value for
nearest bases
string roman[] =
{"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
// Initialize an array of integer which store the corresponding
value of bases
int value[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900,
1000};
// i is the index value of last element of array
int i = sizeof(value)/sizeof(value[0]) - 1;
// Loop until the value of number is greater than 0
while(number > 0) {
// divide the number with ith element of array value array
// Find largest base value for number
int division = number / value[i];
// Store the value of number after removing the base digit
number = number % value[i];
// Print the corresponding roman value of base division times
while(division) {
cout << roman[i];
division--;
}
i--;
}
return 0;
}
Screenshot of code:
Output:
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I
WILL SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------