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
Integer to Roman in C
Given a decimal number n, we have to convert this into Roman numeral. The value n lies in the range 1 to 4000. Roman numerals use specific symbols and follow subtraction rules for certain combinations.
| Number | Numeral |
|---|---|
| 1 | I |
| 4 | IV |
| 5 | V |
| 9 | IX |
| 10 | X |
| 40 | XL |
| 50 | L |
| 90 | XC |
| 100 | C |
| 400 | CD |
| 500 | D |
| 900 | CM |
| 1000 | M |
| 4000 | MMMM |
For example, if the number n = 859, its Roman Numeral will be DCCCLIX.
Syntax
void decToRoman(numeral *nu, int num); int maxNume(numeral *nu, int num);
Algorithm
- Define a structure to store Roman symbols and their corresponding decimal values
- Use a recursive approach where the function finds the largest Roman numeral not exceeding the input number
- Append that numeral to the result and subtract its value from the number
- Repeat until the number becomes zero
Example
The following implementation converts decimal numbers to Roman numerals using a recursive approach −
#include <stdio.h>
typedef struct {
char *sym;
int val;
} numeral;
int maxNume(numeral *nu, int num) {
int i, index = 0;
for (i = 0; i < 13; i++) {
if (nu[i].val <= num)
index = i;
}
return index;
}
void decToRoman(numeral *nu, int num) {
int max;
if (num != 0) {
max = maxNume(nu, num);
printf("%s", nu[max].sym);
num -= nu[max].val;
decToRoman(nu, num);
}
}
int main() {
int number = 859;
numeral nume[13] = {
{"I", 1}, {"IV", 4}, {"V", 5}, {"IX", 9}, {"X", 10},
{"XL", 40}, {"L", 50}, {"XC", 90}, {"C", 100},
{"CD", 400}, {"D", 500}, {"CM", 900}, {"M", 1000}
};
printf("Decimal number: %d<br>", number);
if (number > 0 && number <= 4000) {
printf("Roman equivalent: ");
decToRoman(nume, number);
printf("<br>");
} else {
printf("Invalid Input<br>");
}
/* Test with another number */
number = 3574;
printf("\nDecimal number: %d<br>", number);
printf("Roman equivalent: ");
decToRoman(nume, number);
printf("<br>");
return 0;
}
Decimal number: 859 Roman equivalent: DCCCLIX Decimal number: 3574 Roman equivalent: MMMDLXXIV
How It Works
- The numeral structure stores Roman symbol-value pairs in ascending order
- maxNume() finds the largest Roman numeral that doesn't exceed the input number
- decToRoman() recursively prints the corresponding symbol and reduces the number
- The process continues until the number becomes zero
Conclusion
This recursive approach efficiently converts decimal numbers to Roman numerals by repeatedly finding the largest applicable Roman value and building the result character by character.
Advertisements
