This is a C Program to Convert Roman Number to Decimal Number.
This program takes a roman number as input and converts it to decimal number.
1. Take a roman number as input.
2. Using switch statement define the value of each roman digit.
3. Through switch statement access each digit of a roman number and compute the value.
4. Print the value and exit.
Here is source code of the C program to Convert Roman Number to Decimal Number. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
/*
* C Program to Convert Roman Number to Decimal Number
*/
#include<stdio.h>
#include<string.h>
int digit(char);
int main(){
char roman_Number[1000];
int i=0;
long int number =0;
printf("Enter any roman number (Valid digits are I, V, X, L, C, D, M): \n");
scanf("%s",roman_Number);
while(roman_Number[i]){
if(digit(roman_Number[i]) < 0){
printf("Invalid roman digit : %c",roman_Number[i]);
return 0;
}
if((strlen(roman_Number) -i) > 2){
if(digit(roman_Number[i]) < digit(roman_Number[i+2])){
printf("Invalid roman number");
return 0;
}
}
if(digit(roman_Number[i]) >= digit(roman_Number[i+1]))
number = number + digit(roman_Number[i]);
else{
number = number + (digit(roman_Number[i+1]) - digit(roman_Number[i]));
i++;
}
i++;
}
printf("Its decimal value is : %ld",number);
return 0;
}
int digit(char c){
int value=0;
switch(c){
case 'I': value = 1; break;
case 'V': value = 5; break;
case 'X': value = 10; break;
case 'L': value = 50; break;
case 'C': value = 100; break;
case 'D': value = 500; break;
case 'M': value = 1000; break;
case '\0': value = 0; break;
default: value = -1;
}
return value;
}
1. Take a roman number as input and store it in the array roman_Number.
2. In the function digit(), define the value of each digit of the roman number inside the switch statement and return the same.
3. Using while statement access each digit of the input number.
4. Firstly check if the current roman digit’s value is less than zero. If it is, then print the output as “Invalid roman digit”.
5. If not, then check if the value of current roman digit is greater or equal to its next digit’s value. If it is, then increment the variable number with the value of current roman digit.
6. Otherwise, subtract the value of current roman digit from the value of its next roman digit and increment the variable number with the obtained value.
7. Print the variable number as output.
Output: Enter any roman number (Valid digits are I, V, X, L, C, D, M): XVII Its decimal value is: 17
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Apply for Computer Science Internship
- Check C Books
- Watch Advanced C Programming Videos
- Practice BCA MCQs
- Apply for C Internship