This blog is under construction

Friday 5 July 2013

C program to convert roman number to octal

Please check the below link to know about how to write roman numerals.

Write a C program to convert roman numeral to its octal value.


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

  /* converts given value to its binary equivalent */
  int roman2Deci(char ch) {
        int retVal;
        switch (ch) {
                case 'I':
                        retVal = 1;
                        break;
                case 'V':
                        retVal = 5;
                        break;
                case 'X':
                        retVal = 10;
                        break;
                case 'L':
                        retVal = 50;
                        break;
                case 'C':
                        retVal = 100;
                        break;
                case 'D':
                        retVal = 500;
                        break;
                case 'M':
                        retVal = 1000;
                        break;
                default:
                        printf("Wrong Input!!\n");
                        exit(0);
        }
        return retVal;
  }

  int decimalToOctal(int data) {
        int res = 0, i = 1, mod;

        /* convert decimal to octal */
        while (data > 0) {
                mod = data % 8;
                res = res + (i * mod);
                data = data / 8;
                i = i * 10;
        }

        /* print the resultant octal value */
        printf("Octal Value: %d\n", res);
        return 0;
  }

  int main() {
        char str[100];
        int value, i, j, len;

        /* get the roman numeral from the user */
        printf("Enter your Roman Numeral:");
        fgets(str, 100, stdin);
        str[strlen(str) - 1] = '\0';
        len = strlen(str);

        /* roman to decimal conversion */
        value = roman2Deci(str[len - 1]);

        for (i = len - 1; i > 0; i--) {
                /*
                 * For roman numeral like IV, XL etc, the previous
                 * digit will be lesser than the current digit. So,
                 * we can find their decimal equivalent as follows.
                 * IV => V - I => 5 - 1 => 4
                 * XL => L - X => 50 - 10 => 40
                 */
                if (roman2Deci(str[i]) > roman2Deci(str[i - 1])) {
                        value = value - roman2Deci(str[i - 1]);
                } else {
                        value = value + roman2Deci(str[i - 1]);
                }
        }
        decimalToOctal(value);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your Roman Numeral:XCIX
  Octal Value: 143



No comments:

Post a Comment