Decimal to roman numeral converter in c

C program for Decimal to roman numeral converter. Here mentioned other language solution.

// Include header file
#include <stdio.h>
#include <stdlib.h>
//  C program for
//  Conversion from Decimal to roman number

// Display roman value of n
void  result (int n)
{
    switch (n)
     {
        // Test Cases
        case 1:
            printf("I");
            break;
        case 4:
            printf("IV");
            break;
        case 5:
            printf("V");
            break;
        case 9:
            printf("IX");
            break;
        case 10:
            printf("X");
            break;
        case 40:
            printf("XL");
            break;
        case 50:
            printf("L");
            break;
        case 90:
            printf("XC");
            break;
        case 100:
            printf("C");
            break;
        case 400:
            printf("CD");
            break;
        case 500:
            printf("D");
            break;
        case 900:
            printf("DM");
            break;
        case 1000:
            printf("M");
            break;
    }
}
long selecting(long number, int collection[], int size)
{
    int n = 1;
    int i = 0;
    for (i = 0; i < size; i++)
    {
        if (number >= collection[i])
        {
            n = collection[i];
        }
        else
        {
            break;
        }
    }
    result(n);
    // Reduce the value of number
    return number - n;
}
void  romanNo (long number)
{
    if (number <= 0)
    {
        // When is not a natural number
        return;
    }
    // Base case collection
    int collection[] =
    {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
    // Get the size of collection
    int size = sizeof(collection)/sizeof(collection[0]);
    printf(" %ld : " , number );
    while(number > 0)
    {
        number = selecting(number, collection, size);
    }
    // Add new line
    printf("\n");
}

int main()
{
    // Test Case
    romanNo(10);
    romanNo(18);
    romanNo(189);
    romanNo(604);
    romanNo(982);
    romanNo(3000);
	return 0; 
}

Output

 10 : X
 18 : XVIII
 189 : CLXXXIX
 604 : DCIV
 982 : DMLXXXII
 3000 : MMM



Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2022, kalkicode.com, All rights reserved