Below is a C program which takes a roman number form the user and convert it into a decimal number. We need to understand what the roman number is.

What are Roman Numbers?

The Roman numbers are represented by the combination of letter from Latin alphabets. It is a numeric system that was devised in incant Rome and remained the common of writing numbers throughout Europe.

Example: The numbers from one to ten are written as I, II, III, IV, V, VI, VII, VIII, IX, and X.

C Program to Convert Roman to Decimal

Here is the source code of the program in C to Convert Roman Number to Decimal Number. This program is successfully compiled, and the output is also given below.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int
main (void)
{
  int temp[20];
  char RomNum[2];
  printf ("Enter Roman Number(use Only alphabets I,V,X,L,C,D,M): ");
  scanf ("%s", RomNum);
  int length;
  length = strlen (RomNum);
  for (int k = 0; k < length; k++)
    {
      if (RomNum[k] == 'I')
	temp[k] = 1;
      else if (RomNum[k] == 'V')
	temp[k] = 5;
      else if (RomNum[k] == 'X')
	temp[k] = 10;
      else if (RomNum[k] == 'L')
	temp[k] = 50;
      else if (RomNum[k] == 'C')
	temp[k] = 100;
      else if (RomNum[k] == 'D')
	temp[k] = 500;
      else if (RomNum[k] == 'M')
	temp[k] = 1000;
      else
	{
	  printf ("\nPlease Enter Correct Roman Number and Try Again");
	  exit (0);
	}
    }
  int B;
  B = temp[length - 1];
  for (int j = length - 1; j > 0; j--)
    {
      if (temp[j] > temp[j - 1])
	B = B - temp[j - 1];
      else if (temp[j] == temp[j - 1] || temp[j] < temp[j - 1])
	B = B + temp[j - 1];
    }
  printf ("\nDecimal Number is %d ", B);
  return 0;
}

Output

Convert Roman to Decimal

Program Explanation

Program start execution forms the main function. Take two arrays of size 20 and 2, one is of type int to store corresponding decimal values, and other is of type char to read a roman number form the user.
Use strlen() function to get the length of user entered roman number store it into a length variable. Use for loop to and assign values to temp array of the corresponding Latin letter.

Inside for loop, the if-else statement is used. In if part, corresponding values of the roman number are assigned to temp arrays at appropriate indexes. If there is no match of letters found then else section will be executed.

After the If-Else statement, again for loop is used to calculate the decimal number. The computed value of the roman number is stored in K variable, and the result is printed on the screen.

Related Articles

Last modified: May 3, 2019