Write a general-purpose function to convert any given year into its Roman equivalent. Use these Roman equivalents for decimal numbers:
1 – i, 5 – v, 10 – x, 50 – l, 100 – c, 500 – d, 1000 – m.
Example:
Roman equivalent of 1988 is mdcccclxxxviii.
Roman equivalent of 1525 is mdxxv.
Related Read:
while loop in C programming
else if statement in C
Function / Methods In C Programming Language
Page Contents
Decimal | Roman Equivalent |
---|---|
1000 | m |
500 | d |
100 | c |
50 | l |
10 | x |
5 | v |
1 | i |
Video Tutorial: C Program To Convert Year To Roman Equivalent
#include<stdio.h> void roman(int num) { while(num) { if(num >= 1000) { printf("m"); num = num - 1000; } else if(num >= 500) { printf("d"); num = num - 500; } else if(num >= 100) { printf("c"); num = num - 100; } else if(num >= 50) { printf("l"); num = num - 50; } else if(num >= 10) { printf("x"); num = num - 10; } else if(num >= 5) { printf("v"); num = num - 5; } else if(num >= 1) { printf("i"); num = num - 1; } } printf("\n"); } int main() { int year; printf("Input the year to get its Roman Equivalent\n"); scanf("%d", &year); roman(year); return 0; }
Output 1:
Input the year to get its Roman Equivalent
1988
mdcccclxxxviii
Output 2:
Input the year to get its Roman Equivalent
1525
mdxxv
Output 3:
Input the year to get its Roman Equivalent
2500
mmd
Output 4:
Input the year to get its Roman Equivalent
2020
mmxx
Output 5:
Input the year to get its Roman Equivalent
2021
mmxxi
We ask the user to enter the year in decimal number format and store it inside variable year. Next we pass this user input year to function roman.
Inside function roman, we copy the value of year to a local variable num. We write a while loop and iterate until value of num is positive. Control exits while loop once num is equal to 0.
Inside while loop we check if the value of num is greater than or equal to 1000. If true, then we print roman equivalent of 1000, which is m. And then we decrement the value of num by 1000.
For each iteration of the while loop we check if num is greater than or equal to 1000 or 500 or 100 or 50 or 10 or 5 or 1. To whichever number the value of num matches we printout its corresponding representation in roman:
i.e., 1 – i, 5 – v, 10 – x, 50 – l, 100 – c, 500 – d, 1000 – m.
and also immediately decrement the value by its matched decimal equivalent. We keep doing this until num value is 0.
If user input year is 1525
Iteration | num | Match | Roman Equivalent | New Value of num |
---|---|---|---|---|
1 | 1525 | 1000 | m | 525 |
2 | 525 | 500 | d | 25 |
3 | 25 | 10 | x | 15 |
4 | 15 | 10 | x | 5 |
5 | 5 | 5 | v | 0 |
In above table, last value of num is 0, so control exits while loop. So roman equivalent of year 1525 is mdxxv.
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert