×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to convert a roman number to a corresponding decimal number

Here, we are going to learn how to convert a roman number to a corresponding decimal number in C programming language?
Submitted by Nidhi, on July 03, 2021

Problem statement

Here, we will read a number in the roman format (I, V, X, L, C, D, M) from the user and convert it to a decimal number, and print it on the console screen.

C program to convert a roman number to a corresponding decimal number

The source code to convert a roman number to a corresponding decimal number is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to convert a roman number
// to corresponding decimal number

#include <stdio.h>
#include <string.h>

int getDecimal(char ch)
{
    int num = 0;
    switch (ch) {
    case 'I':
        num = 1;
        break;

    case 'V':
        num = 5;
        break;

    case 'X':
        num = 10;
        break;

    case 'L':
        num = 50;
        break;

    case 'C':
        num = 100;
        break;

    case 'D':
        num = 500;
        break;

    case 'M':
        num = 1000;
        break;

    case '\0':
        num = 0;
        break;

    default:
        num = -1;
    }
    return num;
}

int main()
{
    char romanNum[32] = { 0 };
    int i = 0;
    long int result = 0;

    printf("Enter roman number: ");
    scanf("%s", romanNum);

    while (romanNum[i]) {
        if ((strlen(romanNum) - i) > 2) {
            if (getDecimal(romanNum[i]) < getDecimal(romanNum[i + 2])) {
                printf("Given number is not valid roman number");
                return 0;
            }
        }

        if (getDecimal(romanNum[i]) >= getDecimal(romanNum[i + 1])) {
            result = result + getDecimal(romanNum[i]);
        }
        else {
            result = result + (getDecimal(romanNum[i + 1]) - getDecimal(romanNum[i]));
            i++;
        }
        i++;
    }
    printf("Decimal number : %ld", result);

    return 0;
}

Output

RUN 1:
Enter roman number: III
Decimal number : 3

RUN 2:
Enter roman number: VIII
Decimal number : 8

RUN 3:
Enter roman number: LXXXVIII
Decimal number : 88

RUN 4:
Enter roman number: MX
Decimal number : 1010

Explanation

Here, we created a function getDecimal() to get the decimal number corresponding Roman character.

In the main() function, we created a character array romanNum and also created i, result variables. Then we read a number in roman format. After that, we converted the input roman value into a decimal number and printed the result on the console screen.

C Number System Conversion Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.