Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to convert roman numbers to decimal numbers
Roman numerals are a numeral system that originated in ancient Rome and remained the usual way of writing numbers throughout Europe. In C programming, converting roman numbers to decimal requires understanding the basic roman symbols and their subtraction rule.
Roman Numeral System
The basic roman numerals and their decimal values are −
Conversion Rule
The key rule for roman to decimal conversion is −
- If a smaller numeral appears after a larger one, add it (VI = 5+1 = 6)
- If a smaller numeral appears before a larger one, subtract it (IV = 5-1 = 4)
Algorithm
The conversion algorithm works as follows −
- Convert each roman character to its decimal equivalent
- Compare each value with the next value
- If current value >= next value, add it to result
- If current value < next value, subtract it from result
Example: Complete Program
#include <stdio.h>
#include <string.h>
int main() {
char roman[30];
int deci = 0;
int length, i, d[30];
printf("Roman to Decimal Conversion<br>");
printf("==========================<br>");
printf("Roman Numerals: I=1, V=5, X=10, L=50, C=100, D=500, M=1000<br><br>");
printf("Enter a Roman numeral: ");
scanf("%s", roman);
length = strlen(roman);
/* Convert each roman character to decimal */
for(i = 0; i < length; i++) {
switch(roman[i]) {
case 'm':
case 'M': d[i] = 1000; break;
case 'd':
case 'D': d[i] = 500; break;
case 'c':
case 'C': d[i] = 100; break;
case 'l':
case 'L': d[i] = 50; break;
case 'x':
case 'X': d[i] = 10; break;
case 'v':
case 'V': d[i] = 5; break;
case 'i':
case 'I': d[i] = 1; break;
default:
printf("Invalid roman numeral!<br>");
return 1;
}
}
/* Apply addition/subtraction rule */
for(i = 0; i < length; i++) {
if(i == length-1 || d[i] >= d[i+1])
deci += d[i];
else
deci -= d[i];
}
printf("The decimal equivalent of '%s' is: %d<br>", roman, deci);
return 0;
}
Roman to Decimal Conversion ========================== Roman Numerals: I=1, V=5, X=10, L=50, C=100, D=500, M=1000 Enter a Roman numeral: MCMLIV The decimal equivalent of 'MCMLIV' is: 1954
How It Works
For the input "MCMLIV" (1954) −
- M = 1000, next is C (100) ? 1000 ? 100, so add: 1000
- C = 100, next is M (1000) ? 100 < 1000, so subtract: -100
- M = 1000, next is L (50) ? 1000 ? 50, so add: 1000
- L = 50, next is I (1) ? 50 ? 1, so add: 50
- I = 1, next is V (5) ? 1 < 5, so subtract: -1
- V = 5, last character ? add: 5
- Result: 1000 - 100 + 1000 + 50 - 1 + 5 = 1954
Conclusion
Converting roman numerals to decimal in C involves mapping each roman character to its value and applying the subtraction rule. The algorithm handles both uppercase and lowercase roman numerals correctly.
Advertisements
