MYF

[RA] Ch4 Writing Code

Reading Assignment: All of Programming Ch4 Writing Code

Planning first is not only the best approach for novices, but also for skilled programmers. Having a clear plan of what the program should do at each step makes the debugging process significantly easier.

Step 1: Work an example yourself

The first step to devising an algorithm is to work an instance of the problem yourself. Often, a key part of working the problem yourself is drawing a picture of the problem and its solution. Drawing a clear and precise pictures allows you to visualize the state of the problem as you manipulate it. And it will help you with the next step, in which you write down precisely what you did on this instance of the problem.

An example of computation of overlapped rectangle is given. Hints are given below:

  • Learning to put the obvious aside and think about what is going on is a key programming skill to learn, but takes some time.
  • It is better to spend extra time in an earlier step of programming than getting stuck in a later step(if you do get stuck, you might want to go back to an earlier step and redo it with another instance of the problem).

Step 2: Write down what you just did

Now, you are ready to think about what it was exactly that you just did, and write down a step-by-step approach to solve one specific instance of the problem.

Step 3: Generalize your steps

This step is often the most important and most mistake prone.

Generalizing Values

Generalizing Repetitions

Generalizing Conditional Behavior

Generalization: An Iterative Process

Step 4: Test Your Algorithm

Here are some guidelines to help you devise a good set of test cases to use in Step 4:

  • Try test cases that are qualitatively different from what you used to design your algorithm.
  • Try to find corner cases–inputs where your algorithm behaves differently.
  • Try to obtain statement coverage–that is between all of your test cases, each line in the algorithm should be executed at least once.
  • Examine your algorithm and see if there are any apparent oddities in this behavior.

Step 5: Translation to Code

Composability

You do not have to do anything special to write a loop inside of another loop, nor to write a conditional statement inside of a loop–you can just put the pieces together and they work as expected.

The ability to put things together and have them work as expected is called composability and is important to building not only programs, but other complex systems.

Finishing Our Earlier Examples

A Complete Example

Writing the isPrime function.

Next Steps: Compiling, Running, Testing and Debugging

  • Step 6: Testing your program
  • Step 7: Debugging it