Planning an algorithm

In planning the internal structure of your program, we suggested focusing on variables and event handlers. Each event handler requires you to state what the computer should do when that event occurs, what algorithm it should execute.

One approach to designing algorithms is to solve the problem you want the computer to solve yourself. If you solve the problem yourself, you can then reflect upon the steps you took and instruct the computer to execute the same sequence of steps.

Take for example our payroll program. One of the events it must handle is the user clicking on the Calculate Pay button. When that occurs, we want the computer to calculate the gross pay, tax, net pay and total pay.

Devising an algorithm for that may be confusing at first, but if you try a few examples yourself, you will gain insight into the steps you are following. For example, what if someone works 10 hours at 10 dollars per hour. Can you figure out what the gross pay, tax, net pay and new total pay will be? You would probably do the following:

  1. multiply the hours worked times the hourly rate to get the gross pay ($100)
  2. multiply the gross pay by .2 to get the tax ($20)
  3. subtract the tax from the gross pay to get the net pay ($80)
  4. add the gross pay to the previous total pay to get the new total pay (the old Total Pay + $100)
If you work through a couple of examples by hand, checking your results using the program, you will discover that this is what you are doing. You will have discovered the algorithm you are using by introspection, by paying attention to what you do.

Once you understand the algorithm you are using, it should be fairly easy to translate that into Visual Basic:

  1. sngGross=sngHours*sngRate
  2. sngTax=.2*sngGross
  3. sngNet=sngGross-sngTax
  4. sngTotal=sngTotal + sngGross
(I have used the variable names from the previous note on Internal Design for this example).

Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.