The solution this month’s Exercise isn’t that complex, but it was handy in disproving a theory.

As a recap, the code simulates two opponents in a number game, a player and the computer.

The player goes first, guessing a value, 1 to 3, which is added to a running total. The total starts at zero.

The computer’s job is to also guess values 1 to 3, but with the running total result always a multiple of 4.

The guessing continues until the total surpasses 30.

Here is my solution:

### 2020_08-Exercise.c

#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int total,four,player; /* initialize randomizer */ srand((unsigned)time(NULL)); total = 0; while( total<=30 ) { /* get a value from 1 to 3 */ player=rand() % 3 + 1; total+=player; /* output player's guess and total */ printf("Player adds %d, total is %d\n", player, total ); /* make the computer add a value to equal a multiple of 4 */ four = 4 - total % 4; total += four; printf("Computer adds %d to make %d\n", four, total ); } return(0); }

Variable `total`

represents the game’s running total. It’s initialized to zero at Line 12. The *while* loop spins as long as the `total`

value is less than or equal to 30.

Variable `player`

holds the player’s guess, which is obtained at Line 16: `player=rand() % 3 + 1;`

This value is added to the running total at Line 17: `total+=player;`

After the player’s guess, the computer’s job is easy. Its guess is stored in variable `four`

, which is calculated at Line 25: `four = 4 - total % 4;`

The value in `total`

is divided by 4 to obtain the remainder, which will be values 1, 2, or 3. It can’t ever be zero because the player went first; only the computer can reach a multiple of 4. The result of the modulo operation is subtracted from 4, which means the computer always guesses a multiple of 4.

Here’s a sample run:

`Player adds 3, total is 3`

Computer adds 1 to make 4

Player adds 2, total is 6

Computer adds 2 to make 8

Player adds 3, total is 11

Computer adds 1 to make 12

Player adds 2, total is 14

Computer adds 2 to make 16

Player adds 3, total is 19

Computer adds 1 to make 20

Player adds 2, total is 22

Computer adds 2 to make 24

Player adds 3, total is 27

Computer adds 1 to make 28

Player adds 3, total is 31

Computer adds 1 to make 32

If your solution yields similar results, great! Remember that your code need not match mine to successfully complete the Exercise.

I wrote this simulation to test the theory that going second and always guessing am multiple of 4 helps you to win the 21 number game. It failed. Regardless, in future Lesson I present my version of the 21 number game.