Converting Roman Numerals to Decimal in C

Convert Roman Numerals to Decimal

Today in this article we will be discussing how to Convert Roman Numerals to Decimal.

Lets understand this with the help of example :- 

  • Input:- IX
  • Output:- 9 

IX is a Roman symbol which represents 9

Convert Roman Numerals to Decimal

Algorithm

  • Take a roman number and save it in the array roman_Number.
  • Within the switch statement of the function digit(), define the value of each digit of the roman number and return the same.
  • Using the while statement, iterate through each digit of the input number.
  • First, determine whether the current roman digit’s value is less than zero. If it is, the output should read “Invalid roman digit.”
  • If not, see if the current roman digit’s value is greater or equal to the next digit’s value. If it is, then the variable number is increased by the value of the current roman digit.
  • 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.
  • Print the variable number as output.

Convert Roman Numerals to Decimal

C Code :-

Run
// This function returns value
// of a Roman symbol
#include <stdio.h>
#include <string.h>
#include <stdlib.h>



int value (char r) 
{
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
  return 1000;
  return -1;
 }

  // Returns decimal value of
  // roman numaral
 int romanToDecimal (char str[]) 
 { 
  // Initialize result
  int res = 0;

  // Traverse given input
  for (int i = 0; i < strlen (str); i++)
 {
  // Getting value of symbol s[i]
  int s1 = value (str[i]);

   if (i + 1 < strlen (str))
   { 
   // Getting value of symbol s[i+1] 
   int s2 = value (str[i + 1]); // Comparing both values 
    if (s1 >= s2)
   {
    res = res + s1;
   }
  else
  {
   // Value of current symbol is
   // less than the next symbol
   res = res + s2 - s1;
   i++;
   }
  }
  else
  {
    res = res + s1;
   }
  }
  return res;
}

// Driver Code
int main () 
{
  // Considering inputs given are valid
 char str[10] = "IV";

  printf ("Integer form of Roman Numeral is %d", romanToDecimal (str));
 return 0;

}
Integer form of Roman Numeral is 4