C Program to Convert Roman Number to Decimal Number

Let’s understand how to Convert Roman Num to Decimal Num in C Programming Language.

C Program to Convert Roman Number to Decimal Number

#include <stdio.h>

/*Learn C Programming at CodeAtGlance.com*/

#include<string.h>
int digit(char);
int main(){
    char num1[1000];
    int i=0;
    long int num =0;
    printf("Please enter any roman num (Valid digits are I, V, X, L, C, D, M):  \n");
    scanf("%s",num1);
    while(num1[i]){
          if(digit(num1[i]) < 0){
             printf("Invalid roman digit : %c",num1[i]);
             return 0;
         }
         if((strlen(num1) -i) > 2){
             if(digit(num1[i]) < digit(num1[i+2])){
                 printf("Invalid ");
                 return 0;
             }
         }

         if(digit(num1[i]) >= digit(num1[i+1]))
             num = num + digit(num1[i]);
         else{
             num = num + (digit(num1[i+1]) - digit(num1[i]));
             i++;
         }
         i++;
    }
    printf("Decimal value =%ld",num);
    return 0;
}

int digit(char c){
    int value=0;
    switch(c){
         case 'I': value = 1; break;

         case 'V': value = 5; break;

         case 'X': value = 10; break;

         case 'L': value = 50; break;

         case 'C': value = 100; break;

         case 'D': value = 500; break;

         case 'M': value = 1000; break;

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

         default: value = -1;

    }
    return value;
}

Leave a Reply

Shopping cart