C Exercises: Convert a given roman number to an integer
C Programming Practice: Exercise-7 with Solution
Write a C programming to convert a given roman number to an integer.
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000
C Code:
#include <stdio.h>
#include <stdlib.h>
static int roman_to_integer(char c)
{
switch(c) {
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
return 0;
}
}
int roman_to_int (char *s)
{
int i, int_num = roman_to_integer(s[0]);
for (i = 1; s[i] != '\0'; i++) {
int prev_num = roman_to_integer(s[i - 1]);
int cur_num = roman_to_integer(s[i]);
if (prev_num < cur_num) {
int_num = int_num - prev_num + (cur_num - prev_num);
} else {
int_num += cur_num;
}
}
return int_num;
}
int main(void)
{
char *str1 = "XIV";
printf("Original Roman number: %s", str1);
printf("\nRoman to integer: %d", roman_to_int(str1));
return 0;
}
Sample Output:
Original Roman number: XIV Roman to integer: 14
Pictorial Presentation:
Flowchart:
C Programming Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C programming to convert a given integer to roman number.
Next: Write a C program to find all unique triplets in a given array integers whose sum equal to zero.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
C Programming: Tips of the Day
Static variable inside of a function in C
The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().
The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.
The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().
Ref : https://bit.ly/3fOq7XP
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework