Write a program in c which takes Roman numbers as input and convert it equivalent Decimal number

#include<stdio.h>

#define maxn 10

int value[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
char Roman[][3] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};

//MCDXLVIII = 1448

int Find(char key[]) {
    int i;
    for(i = 12; i>=0; i--) {
        if(!strcmp(Roman[i],key)) return value[i];
    }
    return 0;
}

int Convert(char roman[]) {
    int length = strlen(roman) - 1;
    int i, val, sum = 0, find;
    char tempRoman[4];

    for(i = length; i>=0; ) {
    find = 0;
    if(i >= 1) {
        tempRoman[0] = roman[i-1];
        tempRoman[1] = roman[i];
        tempRoman[2] = NULL;
        val = Find(tempRoman);
        if(val > 0) {
            sum += val;
            find = 1;
            i -= 2;
           }
      }
    if(find == 0) {
        tempRoman[0] = roman[i];
        tempRoman[1] = NULL;
        sum += Find(tempRoman);
        i--;
    }
    }
    return sum;
}

void main() {
 char roman[100];
 clrscr();
 printf("\n Insert a valid Roman number, all characters must be upper case \n lx is an invalid input where LX is a valid input \n Press Clt+z or Clt+c to exit from the program \n Input range: up to 3999 ( MMMCMXCIX ) \n\n");

 while(scanf("%s",roman) != EOF)  {
  printf("%d\n",Convert(roman));
 }
    getch();
}

0 comments:

Post a Comment