Program to convert roman numbers to decimal in C

This is a very standard which is being asked in many interview questions. Here we are going to write the program in C which will convert Roman numbers into decimal number up to 3999 values. Before going ahead let’s revise what each roman literals means:

M = 1000
D = 500
C = 100
L = 50
X = 10
V = 5
I = 1

Click here if you want to see the program to solve the above problem using Interpreter design pattern

Here is C program to solve the above problem.

#include <unistd.h>
#include <stdio.h>
#include <stdbool.h>

#define ROMAN_NUMBER_LENGTH 20

int romanToDecimal (char *ch)
{
	switch (*ch)
	{
		case 'I':
			return 1;
		case 'V':
			return 5;
		case 'X':
			return 10;
		case 'L':
			return 50;
		case 'C':
			return 100;
		case 'D':
			return 500;
		case 'M':
			return 1000;
		default:
			return 0;
	}
}

/* We need to check next char for 'I', 'X' and 'C' character as
 * these characters can come before some other characters which
 * have different values than usual */
int checkNextChar (char *ch, int *index)
{
	bool incrIndex = true;
	int val = 0;
	switch (ch[*index])
	{
		case 'I':
			if (ch [*index + 1] == 'V')
			{
				val = 4;
			}
			else if (ch [*index + 1] == 'X')
			{
				val = 9;
			}
			else
			{
				incrIndex = false;
				val = 1;
			}
			break;
		case 'X':
			if (ch [*index + 1] == 'L')
			{
				val = 40;
			}
			else if (ch [*index + 1] == 'C')
			{
				val = 90;
			}
			else
			{
				incrIndex = false;
				val = 10;
			}
			break;
		case 'C':
			if (ch [*index + 1] == 'D')
			{
				val = 400;
			}
			else if (ch [*index + 1] == 'M')
			{
				val = 900;
			}
			else
			{
				incrIndex = false;
				return 100;
			}
			break;
		default:
			incrIndex = false;
			return romanToDecimal (&ch[*index]);
	}
	if (incrIndex)
	{
		*index = *index + 1;
	}
	return val;
}

int converter (char *roman)
{
	int total = 0;
	for (int i = 0; i < ROMAN_NUMBER_LENGTH ; i++)
	{
		if (roman[i] == '\0')
		{
			break;
		}

		total = total + checkNextChar (roman, &i);
	}
	return total;
}

int main ()
{
	char roman[ROMAN_NUMBER_LENGTH] = "";
	printf ("Enter Roman number: \n");
	scanf ("%s", roman);

	printf ("Entered Number is : %s \n", roman);
	printf ("Equivalent Number is: %d \n", converter (roman));
}

Output of above program is as follows:

Enter Roman number: 
MCDXLIV
Entered Number is : MCDXLIV 
Equivalent Number is: 1444 

Enter Roman number: 
MCDLXVIII
Entered Number is : MCDLXVIII 
Equivalent Number is: 1468 

Leave a Reply

Your email address will not be published. Required fields are marked *