LearnFrenzy
Sign in Take a free test

C Const · const Programs · Question 1

Convert a number to Roman numerals with a const table in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Convert integers to Roman numerals using two parallel static const tables.

Solution
main.c
#include <stdio.h>

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

void print_roman(int n) {
    printf("%d = ", n);
    for (size_t i = 0; i < sizeof values / sizeof values[0]; i++)
        while (n >= values[i]) {
            fputs(symbols[i], stdout);
            n -= values[i];
        }
    putchar('\n');
}

int main(void) {
    print_roman(1994);
    print_roman(2026);
    print_roman(49);
    return 0;
}

Output Verified by compiling and running

1994 = MCMXCIV
2026 = MMXXVI
49 = XLIX

Greedy conversion: repeatedly take the largest value that fits. Listing the subtractive pairs (900 = CM, 4 = IV …) in the table keeps the code trivial. The tables never change, so they are static const.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links