summary refs log tree commit diff stats
path: root/assignments/22-dec-to-roman.c
blob: e4dbef1ce8d07c0f6c82710f7bdfa02df8b27fda (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <stdio.h>

void roman_part(int n, int l, char u, char h, char p)
{
	int i, k; 
	if (n >= l) {
		k = n / l;
		if (k == 9) {
			printf("%c%c", u, p);
		} else if (k >= 5) {
			printf("%c", h);
			for (i = 6; i <= k; i++) {
				printf("%c", u);
			}
		} else if (k == 4) {
			printf("%c%c", u, h);
		} else {
			for (i = 1; i <= k; i++) {
				printf("%c", u);
			}
		}
	}
}

void decimal_to_roman(int n)
{
	int i, k;
	if (n >= 1000) {
		k = n / 1000;
		for (i = 1; i <= k; i++) {
			printf("M");
		} 
	}
	roman_part(n % 1000, 100, 'C', 'D', 'M');
	roman_part(n % 100, 10, 'X', 'L', 'C');
	roman_part(n % 10, 1, 'I', 'V', 'X');
	printf("\n");
}

int main(void)
{
	int n;
	printf("To convert a decimal number to roman number\n\n");
	printf("Enter a number: ");
	scanf("%d", &n);
	if (n < 1 || n > 3999) {
		printf("Invalid input: it must be between 1 and 3999, inclusive.\n");
		return 0;
	}
	decimal_to_roman(n);
	return 0;
}

/*
Output:
Set 1:
To convert a decimal number to roman number

Enter a number: 0
Invalid input: it must be between 1 and 3999, inclusive.

Set 2:
To convert a decimal number to roman number

Enter a number: 123
CXXIII

Set 3:
To convert a decimal number to roman number

Enter a number: 987
CMLXXXVII

Set 4:
To convert a decimal number to roman number

Enter a number: 1234
MCCXXXIV

Set 5:
To convert a decimal number to roman number

Enter a number: 2946
MMCMXLVI

*/