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

PHY3134 Exercise 1: notes

This is a general observation from my observations of peoples programs that I hope will be helpful for future exercises.

Use the same language and notation in your code as when describing the problem.

Most problems have a natural vocabulary and notation in describing them. We use that vocabulary and notation for the names of our variables and structures, their ordering etc.

If instead we devise an elaborate code that we have to decipher to understand, that will occupy a large portion of our intelligence, we will become confused and will make mistakes.

Variable names.

When describing a game of Connect 4 words such as "column" and "row" come naturally to mind. This makes them the best choice to use as variable names (if you're lazy like me you can always use row and col). At the other extreme, calling the horizontal axis "y" and the vertical "x" is asking for trouble.

Row ordering.

Again, when describing the game any of us would refer to the bottom row, the first to be played, as the "first" row. So that's what we call it in our program, either row zero or row one depending on whether we chose to have a one-cell border all around the game.

Of course, when we use the classic loop to print out our grid:

  for(col = 0; col < COLS; ++col) {

the grid will appear upside down. The answer is to simply reverse the order of the loop:

  for(col = COLS - 1; col >= 0; --col) {

Suggestions

  1. Think of how you referred to the rows and columns in your program and ask if that was easier or harder to understand than using the variable names row and column, or col, with the bottom row numbered zero or one.

  2. For future programs, describe the problem to yourself in "normal" language and use those terms as the names of your structures, variables and functions.
                                                                                                                                                                                                                                                                       

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