Hi,
This is an exercise from the deitel book. First i got it to work. Then later it has a bug. There is something wrong with the looping. But i don't know how to explain, sorry. By looking at the code is there something wrong with it?
thnx in advance.
Code:
/* Simpletron - Computer simulation */
#include <stdio.h>
int main()
{
int memory[ 100 ] = { 0 };
int accumulator = 0;
int operationCode;
int operand;
int instructionCounter = 0;
int instructionRegister;
int temp;
printf( "*** Welcome to Simpletron! ***\n" );
printf( "*** Please enter your program one instruction ***\n" );
printf( "*** (or data word) at a time. I will type the ***\n" );
printf( "*** location number and a question mark (?). ***\n" );
printf( "*** You then type the word for that location. ***\n" );
printf( "*** Type the sentinel -99999 to stop entering ***\n" );
printf( "*** your program. ***\n\n" );
while ( memory[ instructionCounter ] != -99999 ) {
printf( "%2d ? ", instructionCounter );
scanf( "%d", &temp );
if ( temp >= -9999 && temp <= 9999 )
memory[ instructionCounter ] = temp;
else if ( temp == -99999 ) {
memory[ instructionCounter ] = temp;
break;
}
instructionCounter++;
}
printf( "\n" );
printf( "*** Program loading completed ***\n" );
printf( "*** Progam execution begins ***\n\n" );
instructionCounter = 0;
while ( instructionRegister != -99999 ) {
instructionRegister = memory[ instructionCounter ];
operationCode = instructionRegister / 100;
operand = instructionRegister % 100;
printf( "\ninstructionRegister = %d, operationCode = %d, operand = %d\n", instructionRegister, operationCode, operand );
switch ( operationCode ) {
case 10:
scanf( "%d\n", &memory[ operand ] );
printf( "scaned for the first time\n" );
break;
case 11:
printf( "%d\n", memory[ operand ] );
break;
case 20:
accumulator = memory[ operand ];
break;
case 21:
memory[ operand ] = accumulator;
break;
case 30:
accumulator += memory[ operand ];
break;
case 31:
accumulator -= memory[ operand ];
break;
case 32:
accumulator /= memory[ operand ];
break;
case 33:
accumulator *= memory [operand ];
break;
case 40:
instructionCounter = operand;
continue;
case 41:
if ( accumulator < 0 ) {
instructionCounter = operand;
continue;
}
break;
case 42:
if ( accumulator == 0 ) {
instructionCounter = operand;
continue;
}
break;
case 43:
printf( "\n\n*** Simpletron execution terminated ***\n\n" );
instructionRegister = -99999;
continue;
default: /* invalid operation code encountered */
printf( "\nSimpletron execution abnormally terminated ***\n" );
instructionRegister = -99999;
continue;
}
instructionCounter++;
}
printf( "\n\n*** END *** \n" );
getch();
return 0;
A sample program which adds two numbers is:
1007
1008
2007
3008
2109
1109
4300
0000
0000
0000
-99999