Skip to content
School of Physics
Home Our Teaching Resources C programming ex6.html
Back to top

Exercises 6

These exercises are not assessed.

Tip: You will use the for() loop quite a few times this week!

  1. Write a function to calculate the dot product of two vectors, of arbitrary length (i.e. the length of the array is passed as one of the arguments). It should return a double. Have main() declare two double arrays (which may be of fixed size), read some values from the screen and print out the dot product.
  2. Simple naughts and crosses.
    1. Have main() declare a 3x3 two dimensional array and initialise it to all zeros. (This could be done either as part of the declaration or by using a double for() loop.)
    2. Write a function to print out the 3x3 grid to the screen in a simple but fairly clear way. (There's no need to get too fancy.)
    3. Now write another function that accepts as its arguments a 3x3 array, and a "player number" which should be one or two. Have it read in the coordinates of the square to be played, checking that the coordinates are valid and the square is empty. Then set the value of that grid-point to the player number.
    4. Have a loop to repeatedly call the "play" function above, followed by the "print" function to enable a simple game to be played.
    5. As time permits, you may like to add either or both of the following:
      • Stop when the grid is full. The simplest way to do this is to have the loop in main() to be a simple for() loop that runs nine times.
      • Write a function to see if a player has won. You could use this to break out of the for() loop. (See week 5 to remind yourself of the break statement.)
                                                                                                                                                                                                                                                                       

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