C - Program - Roman to Integer

To convert a Roman numeral to an integer in C, you can create a mapping between the Roman numeral symbols and their corresponding integer values. Then, iterate through the Roman numeral string, comparing each symbol with its adjacent symbol to determine the appropriate value. Here's an example program that converts a Roman numeral to an integer:

#include <stdio.h>
#include <string.h>
int romanToInt(char* romanNumeral) {
    int length = strlen(romanNumeral);
    int result = 0;
    // Create a mapping of Roman numeral symbols and their corresponding values
    int values[26];
    values['I' - 'A'] = 1;
    values['V' - 'A'] = 5;
    values['X' - 'A'] = 10;
    values['L' - 'A'] = 50;
    values['C' - 'A'] = 100;
    values['D' - 'A'] = 500;
    values['M' - 'A'] = 1000;
    // Iterate through the Roman numeral string
    for (int i = 0; i < length; i++) {
        // Get the value of the current symbol
        int current = values[romanNumeral[i] - 'A'];
        // Check if the next symbol has a higher value
        if (i + 1 < length && values[romanNumeral[i + 1] - 'A'] > current) {
            result += values[romanNumeral[i + 1] - 'A'] - current;
            i++; // Skip the next symbol since it has been considered
        } else {
            result += current;
        }
    }
    return result;
}
int main() {
    char romanNumeral[20];
    printf("Enter a Roman numeral: ");
    scanf("%s", romanNumeral);
    int result = romanToInt(romanNumeral);
    printf("Equivalent integer: %d\n", result);
    return 0;
}

In this program, the romanToInt() function takes a character array romanNumeral as input and converts it to an integer. It initializes a variable result to hold the converted value. It also creates an array values that maps each Roman numeral symbol to its corresponding value.

The function iterates through the characters of the Roman numeral string. For each symbol, it retrieves its corresponding value from the values array. It then checks if the next symbol has a higher value. If so, it subtracts the current symbol value from the next symbol value and adds the result to the result variable. It also increments the loop index to skip the next symbol since it has already been considered. If the next symbol does not have a higher value, it simply adds the current symbol value to the result.

The function continues this process until it has processed all the symbols in the Roman numeral string. Finally, it returns the resulting integer value.

In the main() function, we input a Roman numeral from the user. We call the romanToInt() function, passing the input Roman numeral, and store the returned integer value in a variable. Finally, we print the equivalent integer.