Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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. These are some Roman Numerals.
| 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 |
So if the number n = 859, its Roman Numeral will be DCCCLIX
To solve this, we will follow these steps
- Define an array to store numeral and corresponding values for the given list. That is called nume array
- we are using a recursive approach, the function decToRom() is used. this is taking nume array and the number num.
- The decToRom() will be like
- if num is not 0, then
- max := find maximum value from nume array that is not larger than num
- append the value for that max into the result string
- num := num – max value
- decToRom(nume, num)
Example
Let us see the following implementation to get a better understanding −
#include<stdio.h>
typedef struct{
char *sym;
int val;
}numeral;
int maxNume(numeral *nu, int num){
int i, index;
for(i = 0; i<15; i++){//15 numerals in array
if(nu[i].val <= num)
index = i;
}
//gretest value numeral index, not greater than number
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;//decrease number
decToRoman(nu, num);//recursively print numerals
}
}
main(){
int number;
numeral nume[15] = {{"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},{"MMMM",4000},{"V'",5000}};
printf("Enter a decimal number: ");
scanf("%d", &number);
if(number >0 && number <= 5000){//checking input number
printf("The Roman equivalent of %d is ", number);
decToRoman(nume, number);
}
else{
printf("Invalid Input");
}
printf("
");
}
Input
570 3574
Output
DLXX MMMDLXXIV
Advertisements