Skip to content
Physics and Astronomy
Home Our Teaching Resources C programming week5.html
Back to top

Exercise

The aim here is to improve the game you wrote last week, particularly using some of the text handling we learnt this week.

You will hand in a single piece of work for this week and last week.

Take your previous program and rename main() to a new function, with a sensible name, whose job is to play a single game of noughts and crosses and return zero for a draw or one or two depending on which player won. Remember to have a suitable comment at the start of the function! Now write a new main() that just calls your new function and check it works. At this point your program just does what it did before.

Now make the following improvements:

  1. The playing grid is now a 3x3 array of chars, not ints.
  2. Inside main(), the players are allowed to choose their own non-blank playing character and the unplayed spaces are just blank spaces, ' '. Make sure the characters are different and not the same as the space ' '.
    Tip: use a character array of length two to store the symbols:
      char symbols[2];
    
    Remember: the format for reading a single character skipping over any spaces is " %c" (note the space).
  3. Each player is prompted for their name at the start of the program. For simplicity assume the players names do not have blanks.
    Tip: we could use two character arrays to store the names:
      char name1[NAMELEN], name2[NAMELEN];
    
      printf("Please enter the first name\n");
      scanf("%s", name1);
    

    but a better way is to have an array of two strings, which is just a two-dimensional array of characters:

      char names[2][NAMELEN];
    
      for (int i = 0; i < 2; ++i) {
        printf("Please enter name of player number %d\n", i + 1);
        scanf("%s", name[i]);
      }
    

    Notice how we are allowed to think of names as either a two dimensional array of characters, which needs two indices to refer to a particular character, or a one dimensional array of character strings, which needs just one index to refer to a whole string.

  4. Ask how many games are played, and have a loop that calls your game-playing function that many times and at the end prints out the number of wins and draws, together with "Congratulations name" if one player won over all.

Hand in: Your final code and the printout of the final result of a game. This will be the handin for two weeks work.

                                                                                                                                                                                                                                                                       

Validate   Link-check © Copyright & disclaimer Privacy & cookies Share
Back to top