I'm studying C with a Deitel's book. The book asks me to write a program that simulates a virtual PC (with virtual memory in an array called memory[100]).
Then the book asks me to write a program that sums 10 numbers. I did it but I had to initialize some variables (memory[20], memory[21], memory[22]) before running the program.
There is any way to make this program without initially storing the variables
and using the same number of instructions?
These are valid instructions:
#define READ 10;
#define WRITE 11;
#define LOAD 20;
#define STORE 21;
#define ADD 30;
#define SUBTRACT 31;
#define DIVIDE 32;
#define MULTIPLY 33;
#define BRANCH 40;
#define BRANCHANG 41;
#define BRANCHZERO 42;
#define HALT 43;
And the code:
int main(){
int memory[100] = {2022,1022,3022,2122,2021,3120,2121,4209,4000,1122,4300}; // my set of instruction for sum 10 numbers
memory[99] = -99999;
memory[20] = 1; // the variables initializations that i want to remove
memory[21] = 10;
memory[22] = 0;
int accumulator = 0000;
int instCounter = 00;
int instRegistrer = 0000;
int operationCode = 00;
int operand = 00;
while(memory[instCounter] >= 0){
printf("\n**%d** ", instCounter);
instRegistrer = memory[instCounter];
operationCode = instRegistrer / 100;
operand = instRegistrer % 100;
switch(operationCode){
case READ:
printf("READ ");
scanf("%d", &memory[operand]);
instCounter++;
break;
case WRITE:
printf("WRITE ");
printf("%d", memory[operand]);
instCounter++;
break;
case LOAD:
printf("LOAD ");
accumulator = memory[operand];
instCounter++;
break;
case STORE:
printf("STORE ");
memory[operand] = accumulator;
instCounter++;
break;
case ADD:
printf("ADD ");
accumulator += memory[operand];
instCounter++;
break;
case SUBTRACT:
printf("SUBTRACT ");
accumulator -= memory[operand];
instCounter++;
break;
case DIVIDE:
printf("DIVIDE ");
accumulator /= memory[operand];
instCounter++;
break;
case MULTIPLY:
printf("MULTIPLY ");
accumulator *= memory[operand];
instCounter++;
break;
case BRANCH:
printf("BRANCH ");
instCounter = operand;
break;
case BRANCHANG:
printf("BRANCHANG ");
if(accumulator < 0)instCounter = operand;
else instCounter++;
break;
case BRANCHZERO:
printf("BRANCHZERO ");
if(accumulator == 0)instCounter = operand;
else instCounter++;
break;
case HALT:
printf("HALT ");
instCounter = 99;
break;
}
}
return 0;
}
#definemacros, which will expand tocase 10;:etc. which won't compile. \$\endgroup\$