I'm trying to implement a C program which converts an integer n
(between 0 and 1024) into a Roman numeral by way of a greedy algorithm. I have tried to do this in the following manner:
#include <stdio.h>
#include <string.h>
void convert(int);
int max(int[], int, int);
int main(){
//User Input
int n;
printf("Enter a digit between 0 and 1024: ");
scanf("%d", &n);
//Validation
while((n < 0)||(n > 1024)){
printf("That number is not between 0 and 1024. Please try again: ");
scanf("%d", &n);
}
//Output
printf("\nAs a Roman numeral, this was written: ");
if (n == 0) printf("nulla"); //Romans wrote 'nulla' for zero
else convert(n);
return 0;
}
void convert(int n){
//Case n = 0
if (n == 0) return;
else{
//Case n > 0
char* romanNums[] = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};
int arabicNums[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
int biggestNo = max(arabicNums, 12, n); //Biggest number in arabicNums[] smaller than n
printf("%s", romanNums[biggestNo]); //Print the biggest number as a Roman numeral
convert(n - biggestNo); //Convert the remaining
}
}
//This function determines the maximum number in arr[] smaller than n
int max(int arr[], int size, int n){
int i, max;
for(i = 0; i < size; i++){
if (n < arr[i]) max = i;
}
return max;
}
I have tried debugging and modifying aspects of the code, but it's not working. I'd appreciate any feedback.
UPDATE I've managed to amend my program so that it outputs the values 1, 4, 5 etc. correctly, but composite values (i.e. those which require another iteration of convert()
) keeps resulting in "Romans.exe not responding". Here is the new code:
#include <stdio.h>
#include <string.h>
void convert(int);
int max(int[], int, int);
int main(){
//User Input
int n;
printf("Enter a digit between 0 and 1024: ");
scanf("%d", &n);
//Validation
while((n < 0)||(n > 1024)){
printf("That number is not between 0 and 1024. Please try again: ");
scanf("%d", &n);
}
//Output
printf("\nAs a Roman numeral, this was written: ");
if (n == 0) printf("nulla"); //Romans wrote 'nulla' for zero
else convert(n);
return 0;
}
void convert(int n){
//Case n = 0
if (n == 0) return;
else{
//Case n > 0
char* romanNums[] = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};
int arabicNums[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
int biggestNo = max(arabicNums, 13, n); //Biggest number in arabicNums[] smaller than n
printf("%s", romanNums[biggestNo]); //Print the biggest number as a Roman numeral
convert(n - arabicNums[biggestNo]); //Convert the remaining
}
}
//This function determines the maximum number in arr[] smaller than n
int max(int arr[], int size, int n){
int i, max;
for(i = size; i > 0; i--){
if (n <= arr[i]) max = i;
}
return max;
}