w3resource

C Exercises: Convert a given roman number to an integer

C Programming Practice: Exercise-7 with Solution

Write a C programming to convert a given roman number to an integer.

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

C Code:

#include <stdio.h>
#include <stdlib.h>
static int roman_to_integer(char c)
{
    switch(c) {
    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;
    }
}

int roman_to_int (char *s)
{
    int i, int_num = roman_to_integer(s[0]);

    for (i = 1; s[i] != '\0'; i++) {
        int prev_num = roman_to_integer(s[i - 1]);
        int cur_num = roman_to_integer(s[i]);
        if (prev_num < cur_num) {
            int_num = int_num - prev_num + (cur_num - prev_num);
        } else {
            int_num += cur_num;
        }
    }
    return int_num;
}
int main(void)
 {
  char *str1 = "XIV";
    printf("Original Roman number: %s", str1);
    printf("\nRoman to integer: %d", roman_to_int(str1));
    return 0;
}

Sample Output:

Original Roman number: XIV
Roman to integer: 14

Pictorial Presentation:

C Programming: Convert a given roman  number to an integer.

Flowchart:

C Programming Flowchart: Convert a given roman number to an integer

C Programming Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C programming to convert a given integer to roman number.
Next: Write a C program to find all unique triplets in a given array integers  whose sum equal to zero.

What is the difficulty level of this exercise?



C Programming: Tips of the Day

The tilde operator in C:

The ~ operator is bitwise NOT, it inverts the bits in a binary number:

NOT 011100
  = 100011

Ref : https://bit.ly/3DR1N24