An algorithm is a finite, ordered list of steps that accomplishes a task. "Finite" means it has a definite end. "Ordered" means the sequence matters. You can write an algorithm in plain English, as a diagram or as code.
A program is a set of instructions that a computer can actually carry out. A program is one way to express an algorithm.
An algorithm is only useful if it is precise:
- Each step is an action the reader (or computer) understands.
- The data a step needs is available when that step runs.
- The whole process reaches the intended result.
A program can be neatly formatted and still carry out the wrong algorithm. So before you write any Java, decide what should happen.
The contract of a task is the exact description of what it must do. It has four parts.
| Part | Question it answers | Example |
|---|
| Inputs | What information goes in? | The number of tickets bought |
| Allowed values | Which inputs are permitted? | Whole numbers from 1 to 10 |
| Outputs | What comes out? | The total charge, printed |
| Effects | What else visibly happens? | A newline after the number, a saved receipt |
A request like "calculate the charge" is not finished until these details are known. Is there a fixed fee? Which ticket counts are allowed? Must the printed number end with a newline? When you trace or test a program, use the stated contract. Do not quietly swap in a more convenient one.
Some contracts allow more than one correct output. If a contract says "print both names, one per line, in either order," then two different outputs are both correct, and a fair test must accept either one.