I am currently a student studying c programming and specifically for the final. My teacher posted a final review which I mostly understand except for one program. I am supposed to show what the program displays when it is run.
Code:
#include <stdio.h>#include <stdlib.h>
#define INPUT_LEN 100
#define ARRAY_SIZE 8
typedef struct {
char code;
short val;
} VAL_T;
static VAL_T G_vals[ARRAY_SIZE] = { { 'M', 1000 },
{ 'D', 500 },
{ 'C', 100 },
{ 'L', 50 },
{ 'X', 10 },
{ 'V', 5 },
{ 'I', 1 },
{ '*', 0 } };
short get_val(char code) {
short i = 0;
G_vals[ARRAY_SIZE - 1].code = code;
while (G_vals[i].code != code) {
i++;
}
if (i == ARRAY_SIZE - 1) {
return 0;
}
else {
return G_vals[i].val;
}
}
int compute_value(char *str) {
char *p;
int val = 0;
int next_val;
int remainder;
if (str && *str) {
p = str;
p++;
if (*p == '\0') {
val = get_val(*str);
}
else {
remainder = compute_value(p);
val = get_val(*str);
next_val = get_val(*p);
if (val < next_val) {
val = remainder - val;
}
else {
val = remainder + val;
}
}
printf("Evaluating %s = %d\n", str, val);
}
return val;
}
int main() {
printf("%d\n", compute_value("MCMXCIV"));
getch();
return 0;
}
I put it into a program and the output is:
Code:
Evaluating V=5
Evaluating IV=4
Evaluating CIV=104
Evaluating XCIV=94
Evaluating MXCIV=1094
Evaluating CMXCIV=994
Evaluating MCMXCIV=1994
1994
I am trying to understand the program but I can't seem to get it all. If you could explain each function separately that would be appriciated, that is how I normally understand programs.
Thanks