Algorithmic Thinking with Python. Module 2, algorithms, pseudocode, and flowcharts.

UCEST105 · 42 pages · Your place is saved in this browser

Contents · Module 2 overview
Text size18

Module 2 overview

This module explains how to turn a problem into an algorithm, express its logic in pseudocode, and communicate the same steps with a flowchart.

By the end, you should be able to:

  • Identify the inputs, outputs, assumptions, and steps of an algorithm.
  • Write pseudocode using sequence, selection, and repetition.
  • Read and draw flowcharts using the appropriate symbols.
  • Trace worked examples and check boundary cases before writing code.

Notation used here

SET assigns a value; = inside a condition compares values; MOD gives a remainder. Pseudocode FOR i = 1 TO n includes both endpoints. Python uses different syntax and excludes the stop value of range().

Key idea. An algorithm describes the solution. Pseudocode and flowcharts are two ways of representing that solution.

Start, stop, and flow lines

Terminator

A terminator is an oval or rounded rectangle containing START or STOP. A simple algorithm has one entry point and a clearly marked end.

Rounded START and STOP terminator symbols

Open full-size image

Flow line

A flow line is a line with an arrowhead. Follow its direction to determine the next instruction. Draw the main flow from top to bottom or left to right; avoid crossing lines when possible.

An arrow connects Step 1 to Step 2

Open full-size image

Processing and input/output symbols

Process rectangle

A process rectangle contains a calculation or an assignment, such as total = price × quantity. Write the operation inside the symbol.

A process rectangle containing total equals price times quantity

Open full-size image

Input/output parallelogram

An input/output parallelogram represents reading data or displaying a result. State which values are read or printed. Initializing a variable is a process, rather than an input operation.

An input/output parallelogram for READ age or PRINT fare

Open full-size image

Decisions and continuation connectors

Decision diamond

A decision diamond contains a condition. For a Boolean condition, draw two outgoing branches labelled Yes/No or True/False. Each branch must lead to the appropriate next step.

A decision diamond with separate Yes and No branches

Open full-size image

On-page connector

An on-page connector is a labelled circle that continues the flow elsewhere on the same page.

Off-page connector

An off-page connector is commonly a pentagon pointing downwards and refers to another page. Use matching labels so the reader can find the continuation.

Labelled circle A for an on-page connector and pentagon B for an off-page connector

Open full-size image

Module calls and counter-loop notation

Predefined process

A predefined process is a rectangle with two vertical lines near its sides. It calls a named function or module whose steps are defined elsewhere. Show the call here and explain the called procedure separately.

A predefined-process rectangle with double vertical edges

Open full-size image

The course uses a hexagon for counter-loop notation. Include the counter, starting value, ending value, and step. In other conventions, the same shape represents preparation or initialization, so state the convention you use.

A hexagonal counter-loop symbol showing i equals 1 to n with step 1

Open full-size image

A complete loop still needs a condition, a body, and an update. The worked flowcharts below show these explicitly with process and decision symbols.

Calculate simple interest

Output
START
READ principal, rate, years
SET interest = principal * rate * years / 100
PRINT interest
STOP

Simple-interest flowchart using input/output and process symbols

Open full-size image

Inputs: principal, annual rate as a percentage, and time in years.

Check: principal 1000, rate 5, and time 2 gives interest 100. This is simple interest, not compound interest.

Find the larger of two numbers

Output
START
READ a, b
IF a >= b THEN
    SET largest = a
ELSE
    SET largest = b
END IF
PRINT largest
STOP

Flowchart comparing two inputs, including equal values

Open full-size image

If the inputs are equal, either value is the maximum. For (4, 9) the result is 9; for (7, 7) the result is 7.

Flowchart example: find the smallest of three numbers

Output
SMALLEST
1. START
2. READ a, b, c
3. SET smallest = a
4. IF b < smallest THEN
       SET smallest = b
   END IF
5. IF c < smallest THEN
       SET smallest = c
   END IF
6. PRINT smallest
7. STOP

Flowchart that compares b and c with a running minimum

Open full-size image

Trace

For (8, 8, 3), the candidate minimum starts at 8, stays at 8 after comparing the second value, then becomes 3. Ties do not break this method.

Zoo-ticket selection

Use the following age bands for this separate exercise. They differ from the concert-ticket bands later in the module. Assume age is non-negative.

AgeFare
<10< 1077
≥10 and <60\ge 10 \text{ and } < 601010
≥60\ge 6055
Output
START
READ age
IF age < 10 THEN
    SET fare = 7
ELSE IF age < 60 THEN
    SET fare = 10
ELSE
    SET fare = 5
END IF
PRINT fare
STOP

Zoo-ticket age selection flowchart

Open full-size image

Boundary check

Ages 9, 10, 59, and 60 should give fares 7, 10, 10, and 5 respectively.

Select a colour from its code

CodeMessage
RRRed
GGGreen
BBBlue
Any other valueWrong code
Output
PRINTCOLOUR
1  Start
2  READ(code)
3  caseof (code)
4    case ‘R’:
5      PRINT(“Red”)
6      break
7    case ‘G’:
8      PRINT(“Green”)
9      break
10   case ‘B’:
11     PRINT(“Blue”)
12     break
13   default :
14     PRINT(“Wrong code”)
15 endcase
16 Stop

Colour code selection with a default outcome

Open full-size image

The OTHERWISE or default case handles an unrecognized code. Assume uppercase input; convert lowercase codes first if the program should accept them.

Flowchart example: calculate a factorial

For a non-negative integer nn, the factorial is n!=n×(n−1)×⋯×2×1n! = n \times (n-1) \times \cdots \times 2 \times 1, and 0!=10! = 1.

Output
FACTORIAL
1. START
2. READ n
3. SET fact = 1
4. FOR i = 1 TO n
       SET fact = fact * i
   END FOR
5. PRINT fact
6. STOP

Factorial flowchart with an increasing counter and loop-back arrow

Open full-size image

Trace for n = 4

The product becomes 1, 2, 6, then 24. Reject negative or non-integer inputs before this algorithm starts.

Factorial with a descending counter

The same result can be found by starting at nn and counting down to 1. Initializing fact to 1 also handles n=0n=0, because the loop then runs zero times.

Output
FACTORIAL
1. START
2. READ n
3. SET fact = 1
4. FOR i = n DOWN TO 1
       SET fact = fact * i
   END FOR
5. PRINT fact
6. STOP

Factorial flowchart with a decreasing counter and loop-back arrow

Open full-size image

The product is unchanged by reversing the order of multiplication. The descending counter must decrease on every iteration so that the condition eventually becomes false.

Average height by group

Maintain a separate total and count for each group. This version accepts B or G as group codes and positive heights. It rejects invalid records instead of silently assigning them to a group.

Output
START
READ n
SET boys_total = 0, boys_count = 0
SET girls_total = 0, girls_count = 0
FOR i = 1 TO n
    READ group, height
    IF height <= 0 THEN
        PRINT "Invalid height; record skipped"
    ELSE IF group = "B" THEN
        SET boys_total = boys_total + height
        SET boys_count = boys_count + 1
    ELSE IF group = "G" THEN
        SET girls_total = girls_total + height
        SET girls_count = girls_count + 1
    ELSE
        PRINT "Unknown group; record skipped"
    END IF
END FOR
IF boys_count > 0 THEN
    PRINT boys_total / boys_count
ELSE
    PRINT "No data for boys"
END IF
IF girls_count > 0 THEN
    PRINT girls_total / girls_count
ELSE
    PRINT "No data for girls"
END IF
STOP

Trace

B, 160; G, 150; B, 170 gives a boys' average of 165 and a girls' average of 150. An empty group has no average; never divide by a zero count.

The SVG shows the final count check and average calculation; apply it separately to each group.

Flowchart checking a group count before calculating its average

Open full-size image

References and further reading

The worked examples use the rules stated beside each problem. Ticket prices, grade bands, and commission bands are exercise data, rather than real pricing or institutional policies.

What makes a good algorithm?

Algorithm

An algorithm is a finite sequence of precise, executable steps for solving a problem. It may accept zero or more inputs and must produce the specified result for valid inputs.

PropertyWhat to check
Input and outputAre the required data and expected result clear?
DefinitenessDoes every instruction have one clear meaning?
EffectivenessCan each step actually be carried out?
FinitenessWill the algorithm terminate for valid inputs?
CorrectnessDo its steps meet the problem's requirements?

A common structure is: read input, initialize variables, process the data, display the result, and stop. This is a useful pattern rather than a requirement that every algorithm must read input first.

Before writing the steps, state the assumptions: for example, a factorial needs a non-negative integer, and an average needs at least one value.

Example: compare three numbers

Output
READ a, b, c
IF a >= b AND a >= c THEN
    PRINT a, "is greatest"
ELSE IF b >= c THEN
    PRINT b, "is greatest"
ELSE
    PRINT c, "is greatest"
END IF

Example: area and perimeter of a square

For side length aa, the area is a2a^2 and the perimeter is 4a4a.

Output
READ a
SET area = a * a
SET perimeter = 4 * a
PRINT area, perimeter

Boundary check: for a = 8, b = 8, and c = 3, the greatest value is 8. Using >= prevents tied values from falling through to the wrong branch. For the square example, assume a non-negative side length; a side of 4 gives area 16 and perimeter 16.

Example: swap two values

A temporary variable preserves the first value while the two values are exchanged.

Output
READ a, b
SET temp = a
SET a = b
SET b = temp
PRINT a, b

Trace: if a = 4 and b = 9, then temp = 4, a = 9, and b = 4. A direct a = b followed by b = a would lose the original value of a.

Why use pseudocode?

Pseudocode describes an algorithm in concise, structured language. It is designed for people to read, so it is not tied to the exact syntax of a programming language and cannot be executed directly.

Algorithm, pseudocode, and implementation stages

Open full-size image

Pseudocode bridges an algorithm and its implementation: it makes the planned steps clear before they are translated into program code.

Benefits

  • It is easy to read and understand.
  • It helps plan code before implementation.
  • It lets you review the logic before choosing language-specific syntax.
  • It is helpful for documentation.
  • It can reveal gaps in the logic before coding.

Rules for writing pseudocode

  1. Use consistent keywords for commands and control structures.
  2. Put one instruction on each line.
  3. Indent nested steps to show the structure clearly.
  4. Close each block with a matching keyword such as END IF, END WHILE, or END FOR.
  5. Keep the notation independent of any one programming language.
  6. Use names that describe the problem.
  7. Keep the steps simple, concise, and readable.

Example: find the greatest of three numbers

Output
READ a, b, c
SET greatest = a
IF b > greatest THEN
    SET greatest = b
END IF
IF c > greatest THEN
    SET greatest = c
END IF
PRINT greatest

Flowchart symbol reference sheet

Use this SVG sheet when drawing or checking a flowchart. Each symbol has a distinct role; a process step, input/output step, and decision should remain visually different.

Reference sheet showing all eight Module 2 flowchart symbol groups

Open full-size image

Check a finished chart by tracing at least one path through each decision. Every reachable branch must lead to another step or to a stop, and each loop must make progress toward its exit.

Pseudocode constructs: sequence, selection, and repetition

Sequence

Instructions run in order, from top to bottom.

Selection

Selection chooses which instructions to run based on a condition.

Common forms include:

  • A simple IF
  • An IF/ELSE
  • An IF/ELSE IF chain
  • Nested conditions

Repetition

Repetition runs a group of instructions multiple times.

Common loop forms include:

  • WHILE
  • FOR
  • REPEAT/UNTIL

Simple and nested conditions

A simple IF runs its body only when the condition is true. IF/ELSE selects one of two branches.

Output
IF condition THEN
    statements
END IF

IF condition THEN
    statements when true
ELSE
    statements when false
END IF

A nested condition is an IF inside another conditional block:

Output
IF outer_condition THEN
    IF inner_condition THEN
        statements
    END IF
END IF

Multiple choices with ELSE IF

An ELSE IF chain tests conditions in order. The first true branch runs; if none match, the ELSE branch runs.

Output
IF grade = "A" THEN
    PRINT "Excellent"
ELSE IF grade = "B" THEN
    PRINT "Good"
ELSE IF grade = "C" THEN
    PRINT "Average"
ELSE
    PRINT "Review the grade"
END IF

Only one matching branch is selected.

Case selection and parity checks

A case structure is useful when one value is compared with several specific alternatives.

Output
READ colour_code
CASE colour_code OF
    "R": PRINT "Red"
    "G": PRINT "Green"
    "B": PRINT "Blue"
    OTHERWISE: PRINT "Unknown colour code"
END CASE

Example: test whether an integer is odd or even

Output
READ number
IF number MOD 2 = 0 THEN
    PRINT "Even"
ELSE
    PRINT "Odd"
END IF

Trace a factorial loop

For a non-negative integer nn, n!=n×(n−1)×⋯×2×1n! = n \times (n-1) \times \cdots \times 2 \times 1, and 0!=10! = 1.

Output
READ n
SET factorial = 1
FOR i = 1 TO n
    SET factorial = factorial * i
END FOR
PRINT factorial

When n=0n=0, the loop does not run and the initialized result remains 1.

Iteration for n = 4ifactorial after multiplication
111
222
336
4424

Flowchart: test whether a number is odd or even

For an integer, a remainder of zero after division by 2 means even. A non-zero remainder means odd. This rule also works for zero and negative integers.

Output
START
READ number
IF number MOD 2 = 0 THEN
    SET result = "Even"
ELSE
    SET result = "Odd"
END IF
PRINT result
STOP

Parity flowchart: a zero remainder selects Even; the other branch selects Odd

Open full-size image

InputRemainder modulo 2Result
00Even
60Even
71Odd
-40Even

Concert-ticket pricing rules

For this exercise, a ticket costs 7 for a person under 16, 5 for a person aged 65 or over, and 10 for everyone else. Assume age is a non-negative number.

AgeCharge
Under 167
16 to under 6510
65 or over5
  1. Read age.
  2. If age is under 16, set charge to 7.
  3. Otherwise, if age is at least 65, set charge to 5.
  4. Otherwise, set charge to 10.
  5. Display charge and stop.

Use one selection chain so exactly one band determines the price.

Concert-ticket flowchart

A matching branch goes straight to the output. It must not continue into later price tests, which could overwrite the selected charge.

Concert-ticket flowchart with exclusive age branches and a shared output

Open full-size image

Concert-ticket pseudocode

Output
START
READ age
IF age < 16 THEN
    SET charge = 7
ELSE IF age >= 65 THEN
    SET charge = 5
ELSE
    SET charge = 10
END IF
PRINT charge
STOP

Notice that charge is calculated, not read as an input. The ELSE branch covers ages from 16 up to, but not including, 65.

Check ticket-price boundaries

Boundary values are where an incorrect comparison is easiest to spot. Test the value immediately before a boundary and the boundary itself.

AgeExpected concert chargeWhy
157Under 16
1610First age in the standard band
6410Last whole-number age below 65
655First age in the senior band

Also test a typical age in each band. If negative ages are possible in the input, reject them before applying the pricing rules.

Commission-rate rules

This exercise assigns one rate to the entire sales amount. It does not apply progressive rates to separate portions of the sale.

Sales amountRateDecimal rate
0 to 2000 inclusive2%0.02
Over 2000 to 4000 inclusive4%0.04
Over 4000 to 6000 inclusive7%0.07
Over 60006%0.06

Assume sales is non-negative. The final band deliberately uses the 6% rate from the exercise. Selecting the rate and calculating the commission amount are different steps:

commission amount=sales×rate\text{commission amount} = \text{sales} \times \text{rate}

For sales of 3000, the rate is 0.04 and the commission amount is 120.

Commission pseudocode

Output
START
READ sales
IF sales < 0 THEN
    PRINT "Invalid sales amount"
ELSE
    IF sales <= 2000 THEN
        SET rate = 0.02
    ELSE IF sales <= 4000 THEN
        SET rate = 0.04
    ELSE IF sales <= 6000 THEN
        SET rate = 0.07
    ELSE
        SET rate = 0.06
    END IF
    SET commission = sales * rate
    PRINT rate, commission
END IF
STOP

Boundary check

Sales of 2000, 4000, and 6000 use rates 0.02, 0.04, and 0.07 respectively. A value just above each boundary enters the next band.

Commission-rate flowchart

After validating that sales is non-negative, select one rate using this chart. Calculate the amount as sales × rate when the question asks for the commission amount.

Commission rate flowchart with inclusive upper bounds at 2000, 4000, and 6000

Open full-size image

Repeat-until loops

A repeat-until loop runs its body first, then checks its condition. It always runs at least once and stops when the condition becomes true.

Output
REPEAT
    statements
UNTIL condition

For example, to print 1 through 10:

Output
SET i = 1
REPEAT
    PRINT i
    SET i = i + 1
UNTIL i > 10

Python has no dedicated repeat-until statement. Use while True with a break after the body when the stopping condition is satisfied.

Choose the right control structure

ConstructBest suited toCan run zero times?
IF / ELSEChoosing between alternative actionsNot a loop
FORVisiting a known sequence or counter rangeYes, for an empty range
WHILERepeating while a condition is trueYes
REPEAT / UNTILDoing something before checking whether to stopNo

A loop's condition must be interpreted carefully: WHILE condition continues when the condition is true; UNTIL condition stops when the condition is true.

Example

To print 1 through 10, a while loop can continue while i <= 10, whereas a repeat-until loop can stop when i > 10. Both require an update such as i = i + 1.

Module calls and loop setup

A module call names an already defined procedure, such as calculate_average(values). Its flowchart symbol shows that the work is delegated to that procedure; the procedure's own chart explains the internal steps.

Predefined-process symbol for calling calculate_average

Open full-size image

Before a counter loop starts, define:

  • Its start value.
  • Its limit and whether that limit is included.
  • Its step value.
  • Any running totals or products needed by its body.

The course's hexagonal loop notation is a compact summary of these controls; it does not replace the loop body's instructions.

Sum the first n natural numbers

For this example, sum the integers from 1 through nn, where nn is a non-negative integer. Initialize the total to 0, because no values have been added yet.

Output
START
READ n
SET total = 0
SET i = 1
WHILE i <= n DO
    SET total = total + i
    SET i = i + 1
END WHILE
PRINT total
STOP

Trace for n = 3: the running total becomes 1, then 3, then 6. For n = 0, the loop runs zero times and the result is 0.

Check the result against n(n+1)/2n(n+1)/2.

Keep variable names consistent: total, Total, and TOTAL can denote different names in a programming language.

Example: calculate the average age of students

Read each student's age once, keep a running total, and divide by the number of students. Assume n>0n > 0.

Output
AVERAGE AGE
1. START
2. READ n
3. SET sum = 0, i = 1
4. REPEAT
       READ age
       SET sum = sum + age
       SET i = i + 1
   UNTIL i > n
5. SET average = sum / n
6. PRINT average
7. STOP

Check: three ages of 18, 20, and 22 give a total of 60 and an average of 20. Reject n <= 0 before entering this repeat-until loop.

While loops

A while loop checks its condition before each iteration. The body may run zero times if the condition is false at the start.

Output
WHILE condition DO
    statements
END WHILE

Print the integers from 1 through nn:

Output
SET i = 1
WHILE i <= n DO
    PRINT i
    SET i = i + 1
END WHILE

A for loop is useful when the values or number of repetitions are known in advance. A countdown loop uses a decreasing step.

Watch out. If the body never changes a value used in the condition, the loop may never terminate. In this example, omitting i = i + 1 leaves the condition true indefinitely when n is positive.

For loops and step values

A counter loop specifies its starting value, stopping value, and optional step. The end value is included in this pseudocode convention; Python's range() instead excludes its stop value.

Output
FOR i = 1 TO n
    PRINT i
END FOR

FOR i = 10 TO 1 STEP -1
    PRINT i
END FOR

The step must be non-zero and point toward the stopping value. For the course’s DOWN TO notation, FOR i = 10 DOWN TO 1 already implies a decreasing counter.

Review: selection and repetition patterns

Pseudocode makes control flow explicit. Indent the statements inside each block and close every block with its matching keyword.

Output
IF condition THEN
    statements
ELSE
    statements
END IF

WHILE condition DO
    statements
END WHILE

FOR each item in sequence DO
    statements
END FOR

For example, FOR i = 1 TO n repeats a known number of times, while WHILE condition repeats until its condition becomes false.

Additional Module 2 practice: pseudocode and flowcharts

The following exercises use algorithms and pseudocode. Draw a flowchart for each using the symbols introduced earlier. Python-specific selection, loops, lists, and NumPy belong to Module 3.

Evaluate an expression

For d = a + b * c, multiplication has higher precedence than addition.

Output
START
INPUT a, b, c
product ← b × c
d ← a + product
OUTPUT d
STOP

Print 50 down to 1

Output
START
FOR i ← 50 DOWNTO 1
    OUTPUT i
END FOR
STOP

Sum n input values using each loop form

Count-controlled FOR:

Output
INPUT n
sum ← 0
FOR i ← 1 TO n
    INPUT value
    sum ← sum + value
END FOR
OUTPUT sum

Pre-test WHILE:

Output
INPUT n
sum ← 0
i ← 1
WHILE i ≤ n
    INPUT value
    sum ← sum + value
    i ← i + 1
END WHILE
OUTPUT sum

Post-test REPEAT–UNTIL:

Output
INPUT n
sum ← 0
i ← 1
REPEAT
    INPUT value
    sum ← sum + value
    i ← i + 1
UNTIL i > n
OUTPUT sum

For n = 0, handle the empty input explicitly before entering the repeat-until loop.

The sequence flow for evaluating d = a + b * c is Start → input a, b, c → calculate d → output d → Stop. Draw each step with the matching flowchart symbol; the decision and repetition exercises use decision diamonds and loop-back arrows.

Determine a KTU grade

Use the grade bands supplied by the applicable KTU grading table; the syllabus does not print numerical cutoffs, so do not substitute guessed thresholds. The following are two alternative pseudocode forms using those supplied band limits.

If–else form:

Output
INPUT mark
IF mark ≥ A_PLUS_MIN THEN
    grade ← "A+"
ELSE IF mark ≥ A_MIN THEN
    grade ← "A"
ELSE IF mark ≥ B_PLUS_MIN THEN
    grade ← "B+"
ELSE IF mark ≥ B_MIN THEN
    grade ← "B"
ELSE
    grade ← grade_from_remaining_official_bands(mark)
END IF
OUTPUT grade

Case form:

Output
INPUT mark
band ← official_grade_band(mark)  // look up the same KTU grade table
CASE band OF
    "A+": grade ← "A+"
    "A":  grade ← "A"
    "B+": grade ← "B+"
    "B":  grade ← "B"
    OTHERWISE: grade ← band
END CASE
OUTPUT grade

Trace boundary values from the official table to verify that each mark belongs to exactly one band.

Find the largest of n numbers

Output
INPUT n
IF n ≤ 0 THEN
    OUTPUT "At least one number is required"
ELSE
    INPUT largest
    FOR i ← 2 TO n
        INPUT value
        IF value > largest THEN
            largest ← value
        END IF
    END FOR
    OUTPUT largest
END IF