levo

Elements of Computational Thinking

Thinking logically

  • 1 thing to know
  • Component 02

Overview

Recall questions on decision points, logical conditions and boundary errors, the order conditions are evaluated in, separate if statements versus else if chains, pre-test and post-test loops, dry running decisions, and non-exhaustive conditions.

What you need to know

Answer each one before you reveal it.

Your recallNot started
Key term

What is a decision point, and what determines its outcome?

Questions from this subtopic

Each one with the model answer underneath.

  1. 1

    What is a decision point in a solution, and where do they typically occur?

    Model answer

    A decision point is any place where the path taken by the solution depends on the answer to a question about the current state, so that two different sets of subsequent steps are possible. In a program they show up as selection statements and as the conditions controlling loops. They typically occur: at validation, where input is accepted or rejected; wherever alternative cases exist in the domain, such as different fare bands, tax rates or user roles; at the boundaries of a loop, deciding whether to run the body again; on error, deciding whether to retry, skip or abort; wherever a limit or threshold applies, such as a credit limit, a capacity or an expiry; and at the end of a recursive routine, deciding whether the base case has been reached. Identifying them early matters because each decision point multiplies the number of distinct paths through the solution, and every path is something that has to be designed, tested and reasoned about. A good habit when reading a specification is to underline every occurrence of if, unless, when, otherwise, provided that, up to, at least and more than, because each of those words in the requirements is a decision point in the design.

  2. 2

    A railway ticket machine sells single tickets. Identify the points at which a decision has to be taken.

    Model answer

    Whether the requested destination is one this machine sells tickets to. Whether a valid date and time of travel has been supplied, and whether the requested departure is in the future. Whether the ticket is being bought for today or in advance, since availability and price differ. Whether the time of travel falls in a peak or off-peak band, which is a decision on the day of the week as well as the clock. Whether a railcard or concession has been selected, and if so whether it is valid for this journey, since some carry time restrictions and minimum fares. Whether the passenger is a child, which depends on an age band. Whether a return is cheaper than two singles, which some machines check and some do not. Whether the passenger has enough of a payment method, and whether the payment is authorised. Whether the machine has ticket stock and a working printer, which must be checked before payment. Whether a receipt is wanted. And whether change can be given from the coin float, which is a decision that has to happen before cash is accepted rather than after. Notice that several of these are decisions about the machine's own state rather than about the passenger's request, and those are the ones most often left out of a first design.

  3. 3

    What determines the outcome of a decision? Explain what a logical condition is made of.

    Model answer

    A condition is an expression that evaluates to true or false. At its simplest it is a comparison between two values using a relational operator: equal to, not equal to, less than, greater than, less than or equal to, greater than or equal to. Conditions are combined with the logical operators AND, which is true only if both parts are true, OR, which is true if at least one part is true, and NOT, which reverses a condition. A compound condition can nest these, and brackets settle the order, which matters because A OR B AND C is not the same as the version with the first two bracketed together. Conditions can also test membership, such as whether a value is in a set, or a property, such as whether a string is empty or a file exists. Getting the condition right is the substance of the decision: the same decision point with a slightly wrong condition produces a program that works on most inputs and fails on some, which is the hardest kind of fault to find. Three questions are worth asking of every condition you write: is the comparison the right way round; is the boundary value included or excluded; and have I covered every case, including the ones the requirements document did not mention.

  4. 4

    Off-by-one errors in conditions are extremely common. Show how a boundary can be got wrong and what the consequence is.

    Model answer

    Consider a car park that charges a flat fee for stays of up to two hours and a higher rate beyond that. Written as if duration is less than two hours then charge the flat fee, a stay of exactly two hours falls through to the higher rate, which contradicts up to two hours; it should be less than or equal to. Now consider a discount for customers aged sixty-five and over, written as if age is greater than sixty-five, which silently excludes everyone in their sixty-fifth year. Or a loop that processes a list of n items using positions one to n when the language numbers positions from zero, which either misses the first item or reads one position past the end, and reading past the end may return whatever happens to be in memory rather than raising an error. Or a password rule stated as at least eight characters implemented as greater than eight, rejecting valid eight-character passwords. The consequences share a pattern: the program behaves correctly for almost every input and wrongly for exactly one value, so ordinary testing with typical data passes. That is precisely why boundary value testing exists, and why every threshold should be tested at the value itself, one below and one above.

  5. 5

    Why can the order in which conditions are evaluated change the result?

    Model answer

    For two distinct reasons. The first is short-circuit evaluation, used by most languages: in an AND, if the first part is false the second is never evaluated, and in an OR, if the first part is true the second is never evaluated. This is relied on deliberately, so a test written as if the record exists AND the record's status is active is safe, whereas the same test with the operands swapped attempts to read the status of a record that may not exist and fails. It also means that if the second part has a side effect, such as advancing a counter or writing a log entry, that effect may or may not happen depending on the first part, which is a common source of surprising behaviour. The second reason is the ordering of separate branches in a chain of tests. Where branches are checked in sequence and the first match wins, a broader test placed before a narrower one absorbs the narrower case. A discount scheme that checks if the total is over twenty pounds apply five per cent, otherwise if the total is over a hundred pounds apply fifteen per cent, will never award fifteen per cent, because everything over a hundred is also over twenty and matches the first branch. Ordering from most specific to most general fixes it. Order also matters for validation generally: check that input exists and is of the right type before checking its range, since a range check on a non-numeric value is meaningless.

  6. 6

    Compare a chain of separate if statements with a chain of if, else if, else, and say when each is right.

    Model answer

    A sequence of independent if statements evaluates every condition, and more than one branch can run. That is what you want when the conditions are independent and their actions can legitimately combine, for example applying several separate surcharges to an order where a customer might qualify for more than one. A chain of if, else if, ending in else evaluates conditions in order and executes at most one branch, stopping at the first that matches. That is what you want when the cases are mutually exclusive alternatives, such as assigning a single grade band or a single fare class, and it is both faster, since later conditions are not evaluated once a match is found, and safer, because it makes it structurally impossible for two mutually exclusive cases to both fire. The classic bug is using independent if statements for exclusive cases: a grading routine that says if the mark is at least seventy award a distinction, if the mark is at least fifty award a pass, will award a pass to a mark of eighty-five, overwriting the distinction, because both conditions are true. The final else also matters: it catches everything not otherwise handled, and omitting it means an unforeseen case falls through with no action and no error, which is how a value ends up unset.

Other ways to work this

The same content, four other ways.

What is inside Levo

Six ways to work the same material.

1Closed book
2Open book
3Closed book

The 3-step method, run for you

Answer cold, learn it, then prove it stuck. Levo tracks the jump between your first attempt and your last.

Processors: Structure, Performance and Types
Input, Output and Storage
Systems Software
Applications Generation

Cram a whole paper in one sitting

Sort every topic into what you know and what you do not, then drill only the weak ones.

If it matches, the search .
succeedsfailsrestarts

Blank Blitz makes facts automatic

Rapid timed gap-fills on the terms and numbers you need to recall without thinking.

A0 + 0 gives 0.
B0 + 1 gives 1.
C1 + 1 gives 0 carry 1.

Build It gets the exam shape right

Assemble a full-mark answer from its marking points, in the order an examiner wants them.

A global variable means a variable reachable from anywhere in the program.
TrueFalse

Test It catches misconceptions

Spot the fault in a statement. The traps are the mistakes students actually make.

721941163128510

Brain Breaks between sessions

Short focus games to reset attention, so the next set lands better than the last.

Every question in Elements of Computational Thinking, on a schedule.

Attempt a question from memory, write the correct version, then attempt it again. Levo records the jump between your first attempt and your last, and brings each question back on the day you are due to forget it.

Or £46 a year, about £3.83 a month. Cancel anytime.