Unit 1 · Basics of Computer Programming

1.2.2Worked examples

Worked example: Largest of two numbers

Draw the following, joined by arrows in this order:

  1. Oval: Start
  2. Parallelogram: Read a, b
  3. Diamond: Is a > b?
  4. Yes exit: Rectangle: largest = a. No exit: Rectangle: largest = b.
  5. Both exits join, then Parallelogram: Display largest
  6. Oval: Stop
StartREAD a, ba > b ?largest = alargest = bPRINT largestStopYesNo
Flowchart: the largest of two numbers (selection)

Reading the chart: this is selection. There is one decision, so there are two possible paths through the chart, and exactly one is followed each time. Notice that both paths join before Display largest, so the output step is written only once. Dry run it with a = 3 and b = 8: 3 > 8 is No, so largest = b = 8, and 8 is displayed.

Worked example: Sum of 1 to N

  1. Oval: Start
  2. Parallelogram: Read N
  3. Rectangle: total = 0, i = 1
  4. Diamond: Is i <= N?
  5. Yes exit: Rectangle: total = total + i, then Rectangle: i = i + 1, then an arrow back up to the diamond in step 4 (this arrow forms the loop)
  6. No exit: Parallelogram: Display total
  7. Oval: Stop
StartREAD Ntotal = 0, i = 1i <= N ?total = total + ii = i + 1Yesloop backNoPRINT totalStop
Flowchart: the sum of 1 to N (iteration). The arrow back to the decision forms the loop

Tip: A loop in a flowchart always has a diamond with one exit leading out and one path returning to before the diamond.

Reading the chart: this is iteration. The decision i <= N? is tested before every pass, so if N is 0 the body never runs and 0 is displayed, which is the correct sum of no numbers. Dry run it with N = 3: the total becomes 1, 3 and then 6, i reaches 4, the test 4 <= 3 is No, and 6 is displayed.

Worked example: Grade from marks (several decisions)

Problem: read marks and display A (75 or more), B (65 to 74), C (50 to 64) or F (below 50). Draw:

Why test 75 first? Because a mark of 80 is also 65 or more and 50 or more. Testing from the highest band down means the first Yes answer is always the right grade, and each later diamond only has to check the lower limit of its band.

Try it: dry run the grade flowchart with the marks 75, 64 and 49. You should get A, C and F. These are boundary values: 1.4.2 explains why they are the most important values to test.