This is a sample program that my tutor gave me. However, I have very much trouble understanding the second if statement. Would somebody plz be able to explain it to me, in not too difficult language![]()
Code:#include <stdio.h> //Handles the keyboard input and screen output #include <process.h> //Handles DOS system commands ("cls", "pause", etc.) #include <conio.h> //Handles: getch(), getche(). #include <string.h> //Handles string functions. int main(void) { //This part declares variables used by the entire program int Arabic=0; //Integer declaration to store Arabic number char Roman[30]; //String declaration to store a Roman number //This part declares variables used and reads Arabic numbers int counter = 7; //Declares the count of digits in Roman numbers char T_Roman [7] = "MDCLXVI"; //Lists all digits of Roman numbers int T_Arabic [7] = {1000, 500, 100, 50, 10, 5, 1};//Values of Roman digits int length=0; //Stores the length of an input Roman number int in, list; //Declare operational loop counters int last_in, last_list;//Store the previous digits being considered textcolor(6); //This defines color of the writing for "cprintf" cprintf("This program converts Roman numbers into Arabic numbers.");//Colour //This part reads Raman numbers with "scanf" and "printf" printf("\nType a valid Roman number (e.g. MCMXCIX) up to 30 chars long: "); scanf("%s", Roman); //Inputs a Roman number length = strlen(Roman); strupr(Roman); printf("The Roman number |%s| is %d characters long.", Roman, length); fflush(stdin); //flushes the input buffer //This part contains the algorithm of converting Roman numbers into Arabic: in=0; last_in = length + 1; last_list = length + 1; while (in < length) //Loop along the chars of the Roman number { for(list=0; list < counter; ++list) //Loop along the Roman symbols { if (Roman[in] == T_Roman[list]) { /*printf ("\nRoman digit |%c| matched to |%c| = %4d.", Roman[i], T_Roman[j], T_Arabic[j]); */ if ((last_in == (in-1)) && (last_list > list)) Arabic = Arabic - 2*T_Arabic[last_list]; last_in = in; last_list = list; Arabic = Arabic + T_Arabic[list]; } } in=in+1; } //This part displays the results printf("\nThe Roman number |%s| converts into Arabic %d.", Roman, Arabic); //This part finishes the program puts ("\nNormal end of program. BYE."); //gotoxy(20,7); //Position at "character no", "line no" printf("\n"); system("pause"); //DOS "Pause" command (for user to look at results) }



LinkBack URL
About LinkBacks




What this does is handle special cases such as CD by checking to see if the last converted character is farther along the search string, and thus lower in value, than the current character. That way the program knows to subtract the necessary amount so that the addition later will result in the correct value.
But I'm open to suggestions for alternatives. 