|
|
|
|
|
|
|
Figure 1-1
Programming Process |
|
|
|
|
|
|
|
|
When you start your car, you follow a step-by-step procedure. The algorithm might look something like this: |
|
|
|
|
|
|
|
|
2. Make sure the transmission is in Park (or Neutral). |
|
|
|
|
|
|
|
|
3. Depress the gas pedal. |
|
|
|
|
|
|
|
|
4. Turn the key to the start position. |
|
|
|
|
|
|
|
|
5. If the engine starts within six seconds, release the key to the ignition position. |
|
|
|
|
|
|
|
|
6. If the engine doesn't start in six seconds, release the key, wait ten seconds, and repeat steps 3 through 6, but not more than five times. |
|
|
|
|
|
|
|
|
7. If the car doesn't start, call the garage. |
|
|
|
|
|
|
|
|
Without the phrase but not more than five times in step 6, you could be trying to start the car forever. Why? Because if something is wrong with the car, repeating steps 3 through 6 over and over again will not start it. This kind of never-ending situation is called an infinite loop. If we leave the phrase but not more than five times out of step 6, the procedure does not fit our definition of an algorithm. An algorithm must terminate in a finite amount of time for all possible conditions. |
|
|
|
|
|
|
|
|
Suppose a programmer needs an algorithm to determine an employee's weekly wages. The algorithm reflects what would be done by hand: |
|
|
|
|
|
|
|
|
1. Look up the employee's pay rate. |
|
|
|
|
|
|
|
|
2. Determine the number of hours worked during the week. |
|
|
|
|
|
|
|
|
3. If the number of hours worked is less than or equal to 40, multiply the number of hours by the pay rate to calculate regular wages. |
|
|
|
|
|