Weeks
Computational ThinkingWeek 1 · Flowcharts, Datatypes, Records and Lists
Week 1 Notes

Computational
Thinking 1

Flowcharts, iteration with filtering, and the data types that keep our data sane. Lectures 1.4 to 1.10.

7 chapters36 worked examples~42 min read
FlowchartsIterationFilteringData typesRecords & Lists

Chapters

  1. 01Introduction to FlowchartsLecture 1.4
  2. 02Flowchart for Sum with FilteringLecture 1.5
  3. 03Introduction to DatatypesLecture 1.7
  4. 04Subtypes of Basic DatatypesLecture 1.8
  5. 05Transformation of Sub-datatypesLecture 1.9
  6. 06Introduction to Complex DatatypesLecture 1.10
  7. 07Week 1 Summary SheetAll lectures
01
Lecture 1.4

Introduction to Flowcharts

A flowchart draws a program as boxes joined by arrows, so we can see the order in which steps run and which path is taken. We build flowcharts for two small tasks on a pile of cards: counting the cards and summing the Maths marks.

1.1Commonly used symbols

Terminal
Start / End

Indicates the start or end of the program.

Process
Process or activity

A set of operations that change the value of data (variables), like Sum = 0.

Flowline
Flowline or arrow

Shows the order of execution of the program steps.

Decision
Decision

Determines which path the program will take, e.g. X is a boy?.

A decision has two outcomes

Every decision box has exactly two ways out: Yes (True) or No (False). The condition inside the box is answered with one of them.

1.2Flowchart for counting cards

Goal: find how many cards there are. At the start all the cards are in a single pile, called Pile 1. We build the flowchart one idea at a time.

  1. Start. The cards are all assumed to be in Pile 1.
  2. Initialise the variable count = 0.
  3. Repeat these steps: pick a card from Pile 1, move it into a different pile (say Pile 2), and increment count. The iteration stops when Pile 1 is empty.
  4. Check first. We can only pick a card if there are more cards in Pile 1, so we ask the decision "More cards in Pile 1?"
  5. No (False): no more cards, so the program can End. The variable count carries the required value.
  6. Yes (True): pick a card from Pile 1 and call it X.
  7. Move X to Pile 2 so that we never visit card X again.
  8. Increment count, then go back to the beginning of the iteration (the decision box).
Start / EndProcessDecisionStartCount = 0More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2Increment countInitialisationPut all cards in Pile 1and set count to 0Iterative steps• Pick a card• Move card to Pile 2• Increment count
Figure 1. Flowchart for counting cards
Pattern to remember

Every flowchart here has two parts: an initialisation before the loop, and a set of iterative steps that repeat while the decision answers Yes.

1.3Flowchart for sum of Maths marks

To get the sum of Maths marks we reuse the counting flowchart and change only two things:

  • Initialise Sum = 0 instead of count = 0.
  • Replace Increment count with Add CardX's Maths score to Sum.

The rest of the flowchart remains the same.

Start / EndProcessDecisionChanged from the previous flowchartStartSum = 0More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2Add CardX's Maths score to SumInitialisationPut all cards in Pile 1and set sum to 0Iterative steps• Pick a card• Move card to Pile 2• Accumulate in Sum
Figure 2. Flowchart for sum of Maths marks

1.4Generic flowchart for iteration

Both flowcharts follow one template. We keep going while there are unvisited elements: pick one, mark it as visited, and update the variables.

Start / EndProcessDecisionStartInitialiseMore cardsin Pile 1?No (False)EndYes (True)Pick an unvisited elementMark element as visitedUpdate variablesInitialisationSet the variables(count, sum, ...)Iterative steps• Pick• Mark visited• Update variables
Figure 3. Generic flowchart for iteration
Generic stepCounting cardsSum of Maths marks
InitialiseCount = 0Sum = 0
Unvisited elements?More cards in Pile 1?More cards in Pile 1?
Pick an unvisited elementPick a card X from Pile 1Pick a card X from Pile 1
Mark element as visitedMove X to Pile 2Move X to Pile 2
Update variablesIncrement countAdd CardX's Maths score to Sum
Example 1Tracing the counting flowchart

Pile 1 has 3 cards: A, B, C. Trace the counting flowchart and write the value of count after each pass.

Solution
PassMore cards in Pile 1?Card pickedcount
—start: all in Pile 1—0
1YesA → Pile 21
2YesB → Pile 22
3YesC → Pile 23
checkNo—End, count = 3

The decision is asked one more time than there are cards: 3 Yes answers and a final No.

Example 2Tracing the sum flowchart

Three cards have Maths scores 40, 70 and 55. Trace the sum flowchart.

Solution
PassCard XMaths scoreSum
———0
1A400 + 40 = 40
2B7040 + 70 = 110
3C55110 + 55 = 165

When Pile 1 is empty the program ends with Sum = 165.

Example 3Why do we move X to Pile 2?

Suppose we forget the step Move X to Pile 2. What goes wrong?

Solution
  • The card X stays in Pile 1, so the decision More cards in Pile 1? is still Yes.
  • We would pick a card again and again (possibly the same one), the pile never empties, and the loop never ends.
  • Marking an element as visited is what makes sure every card is handled exactly once.

1.5How the loop really works

Do not just memorise the picture. Every box in the flowchart is there for a reason, and if you know the reason you can rebuild any iteration flowchart in the exam, even for a problem you have not seen.

  1. Check before you pick. The decision More cards in Pile 1? comes first. So the flowchart also works when Pile 1 is empty: the answer is No at once, the program ends, and count stays 0, which is the correct answer.
  2. Every pass must make progress. Move X to Pile 2 removes exactly one card from Pile 1. After n passes the pile is empty and the loop is guaranteed to stop. Without this step the loop never ends.
  3. Initialise outside the loop. count = 0 must run once. If it sat inside the loop it would reset to 0 on every pass and the answer would be wrong.
  4. Counting and summing are the same flowchart. Only the variable and its update change. For any new problem ask two questions: what do I initialise? and what do I update for each card?

How many times does each box run for n cards?

BoxRunsWhy
Start, initialise, End1once per program
More cards in Pile 1?n + 1n times Yes, then one final No
Pick X, Move X to Pile 2, update variablenonly on the Yes path, once per card

1.6Exam tips and common mistakes

Exam tips
  • Draw in the same order every time: initialisation, decision, loop body, loop-back arrow.
  • For a trace question make a table with columns Pass, Card, variable. Fill one row per card and add one last row for the final No.
  • Count questions: n cards means the decision is evaluated n + 1 times and the loop body runs n times.
  • Label both exits of every decision box (Yes/True and No/False).
  • The loop-back arrow goes to the decision More cards in Pile 1?, never to Start.
Common mistakes
  • Writing Sum = 0 inside the loop. The sum resets every pass, so you end with only the last card's score.
  • Forgetting Move X to Pile 2. The pile never empties and the loop runs forever.
  • Sending the loop-back arrow to Start. All the variables get re-initialised.
  • Using a Process box for a question. A question with two exits is a Decision; a Process box changes data and has one exit.

Practice questions (graded-assignment style)

Q1Counting the decision

Multiple Choice Question (MCQ): choose the one correct option.

Pile 1 has 8 cards. The counting flowchart is run. How many times is the decision More cards in Pile 1? evaluated?

1
7
2
8
3
9
4
16
Solution
Idea

Every card gives one Yes. One final No ends the loop. So the decision runs n + 1 times.

  • 8 cards give 8 Yes answers, one per pass.
  • After the last card, Pile 1 is empty, so the decision is asked once more and answers No.
  • Total: 8 + 1 = 9. Option 1 and option 2 forget the final No. Option 4 would need two checks per card, but each card is checked once.
  • Answer: option 3.
Q2Rules of an iteration flowchart

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements about an iteration flowchart.

1
Variables such as Sum are initialised before the loop.
2
The loop-back arrow goes to Start.
3
Move X to Pile 2 guarantees that the loop terminates.
4
A decision box has exactly two exits.
Solution
Idea

Initialise once, outside. Every pass must shrink the pile. A decision branches two ways.

  • Option 1 is correct: initialising inside the loop would reset the variable on every pass.
  • Option 2 is wrong: going back to Start would re-initialise everything. The arrow returns to the decision More cards in Pile 1?.
  • Option 3 is correct: each pass removes one card, so the pile is empty after n passes.
  • Option 4 is correct: Yes (True) or No (False).
  • Answer: options 1, 3 and 4.
Q3Initialisation in the wrong place

Numerical Answer Type (NAT).

By mistake Sum = 0 is written inside the loop, before the add step. The cards have Maths scores 25, 40 and 35. What is the final value of Sum?

Solution
Idea

If the variable is reset on every pass, only the last card survives.

  • Pass 1: reset to 0, add 25, Sum = 25.
  • Pass 2: reset to 0, add 40, Sum = 40.
  • Pass 3: reset to 0, add 35, Sum = 35.
  • The correct total would be 100, which needs Sum = 0 before the loop.
  • Answer: 35
Revision overview
SymbolsTerminal: Start / End
Process: changes data
Decision: picks the path
Flowline: order of steps
Counting cardsCount = 0, all cards in Pile 1
Pick card, move to Pile 2
Increment count
Stop when Pile 1 is empty
Sum of Maths marksSum = 0 instead of Count = 0
Add Maths score of X to Sum
Rest of flowchart is the same
FlowchartsLecture 1.4
Generic iterationInitialise
Unvisited elements?
Pick, mark visited, update
Decision outcomesYes (True): run the loop body
No (False): go to End
Loop backAfter the last step, go back
to the start of the iteration
Revision: everything in Lecture 1.4 on one page
Next · Lecture 1.5Flowchart for Sum with Filtering
02
Lecture 1.5

Flowchart for Sum with Filtering

Sometimes we want to add up only some of the cards. Here we only add up the cards that pass a test, which is called filtering. We start from the sum flowchart of Lecture 1.4.

2.1Sum of Boys' Maths marks

Goal: add the Maths marks of the boys only. Think about how to modify the flowchart:

  1. After Move X to Pile 2, we have to do something before we add to Sum.
  2. We check if X is a boy. This is a new decision box.
  3. Yes (True): add CardX's Maths score to Sum.
  4. No (False): nothing to be done if X is a girl, so we simply go back to the loop.
Start / EndProcessDecisionChanged from the previous flowchartStartSum = 0More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2X is a boy?Yes (True)Add CardX's Maths score to SumNo (False)
Figure 4. Flowchart for sum of Boys' Maths marks
Filter condition. The decision X is a boy? is added inside the iteration. When X is a girl there is nothing to do, so that branch just returns to the loop.

2.2Sum of both Boys' and Girls' Maths marks

To get both totals at once we keep two sums. The No (False) branch is no longer empty: it adds the score to GirlSum.

Start / EndProcessDecisionChanged from the previous flowchartStartGirlSum = 0BoySum = 0More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2X is a boy?Yes (True)No (False)Add CardX's Mathsscore to BoySumAdd CardX's Mathsscore to GirlSumBoth paths go back to the same place in the iteration
Figure 5. Boys' and girls' Maths marks together
Key idea

The filter condition goes inside the iteration. Whichever way the decision goes, both paths go back to the same place, the check More cards in Pile 1?, so every card is still visited exactly once.

FlowchartVariablesYes (True)No (False)
Boys' marks onlySumAdd Maths score to SumDo nothing
Boys and girlsBoySum, GirlSumAdd Maths score to BoySumAdd Maths score to GirlSum
Example 4Tracing the boys-only sum

Four cards (Maths score, gender): A (60, M), B (75, F), C (50, M), D (90, F). Trace the flowchart for the sum of boys' Maths marks.

Solution
CardX is a boy?ActionSum
——initialise0
A (60, M)Yesadd 6060
B (75, F)Nodo nothing60
C (50, M)Yesadd 50110
D (90, F)Nodo nothing110

Final answer: Sum = 110.

Example 5Boys and girls together

Use the same four cards with the flowchart that keeps BoySum and GirlSum.

Solution
  • Boys (A, C): BoySum = 60 + 50 = 110.
  • Girls (B, D): GirlSum = 75 + 90 = 165.
  • Check: BoySum + GirlSum = 275 = 60 + 75 + 50 + 90, the sum over all cards. Every card was added to exactly one of the two sums.
Example 6Count the boys

How would you change the filtering flowchart to count the number of boys instead?

Solution
  1. Initialise BoyCount = 0 (instead of Sum = 0).
  2. Keep the decision X is a boy? inside the iteration.
  3. On Yes (True), replace Add CardX's Maths score to Sum with Increment BoyCount.
  4. On No (False) do nothing. The pattern is unchanged: only the variable and the update differ.

2.3Where the filter goes, and why

A filter is just an if inside the loop. The loop decides which cards we look at (all of them, once each). The filter decides what we do with each card.

  1. Mark the card as visited on every path. Move X to Pile 2 comes before the filter decision, so both Yes and No paths have already done it. If you moved X only inside the Yes branch, a girl's card would stay in Pile 1 for ever and the loop would never end.
  2. Skip, or split. A one-sided filter (No does nothing) needs one variable. A two-sided filter (both branches update something) splits the cards into two groups, and each card lands in exactly one. So BoySum + GirlSum equals the sum over all cards, and the two counts add up to n. Use this to check your answer.
  3. Combined conditions. For "boys scoring above 50" use two decisions one after the other (the second only on the Yes of the first), or one decision with AND. The score is added only on the Yes-Yes path. Every No exit goes straight back to More cards in Pile 1?.
  4. Average needs two variables. Keep a sum and a count, both updated on the Yes path. Divide after the loop has ended, and make sure the count is not 0.

Which variables for which question?

QuestionVariables to initialiseOn the Yes path
Sum of boys' Maths marksSumadd X's Maths score
Number of girlsGirlCountIncrement GirlCount
Average of boys' Maths marksBoySum, BoyCountadd the score and increment the count
Boys scoring above 50Sumsecond decision: score > 50? then add

2.4Exam tips and common mistakes

Exam tips
  • Read the question and underline three things: who is included (the filter), what is computed (sum, count, average) and how many variables you need.
  • Say where the decision sits: inside the iteration, after Move X to Pile 2.
  • Every exit of the filter returns to More cards in Pile 1?.
  • Two groups means two variables, both initialised to 0.
  • Check yourself: the group totals must add up to the overall total.
Common mistakes
  • Putting the filter outside the loop. It would test one card only.
  • Moving X to Pile 2 only on the Yes branch. The No branch never empties the pile.
  • Sending the No branch to End. The program stops early and the remaining cards are never seen.
  • Forgetting to initialise the second variable (GirlSum) to 0.
  • Swapping the Yes and No labels on the decision.

Practice questions (graded-assignment style)

Q1Two sums

Numerical Answer Type (NAT).

Cards (Maths score, gender): A (60, M), B (75, F), C (50, M), D (90, F). The flowchart keeps BoySum and GirlSum. Find GirlSum − BoySum.

Solution
Idea

The Yes path feeds one sum and the No path feeds the other, so each card goes to exactly one.

  • Boys: A and C, BoySum = 60 + 50 = 110.
  • Girls: B and D, GirlSum = 75 + 90 = 165.
  • Difference: 165 − 110 = 55.
  • Check: 110 + 165 = 275 = 60 + 75 + 50 + 90.
  • Answer: 55
Q2Where does Move X go?

Multiple Choice Question (MCQ): choose the one correct option.

In the filtering flowchart, where must Move X to Pile 2 be placed so that the loop always ends?

1
Only on the Yes branch
2
Before the filter decision, so every path has it
3
Only on the No branch
4
After End
Solution
Idea

Every card must be marked visited, whichever way the filter decides.

  • Option 1: a card that fails the filter would stay in Pile 1 for ever, so the loop never ends.
  • Option 2: both Yes and No paths already moved X, so each pass removes one card.
  • Option 3: the same problem for cards that pass the filter.
  • Option 4: nothing after End ever runs.
  • Answer: option 2.
Q3Boys who scored above 50

Multiple Select Question (MSQ): select all that apply.

Cards (Maths score, gender): A (40, M), B (70, F), C (55, M), D (80, M). The flowchart adds the score only if X is a boy and the score is above 50. Choose the correct statements.

1
The final Sum is 135.
2
Card A is skipped by the second decision.
3
Card B reaches the second decision.
4
If only "score > 50" were checked, Sum would be 205.
Solution
Idea

Trace each card through both decisions. A card is added only on the Yes-Yes path.

  • A: boy, 40 > 50 fails, skipped. B: girl, stops at the first decision. C: boy, 55 > 50, add 55. D: boy, 80 > 50, add 80.
  • Sum = 55 + 80 = 135, so options 1 and 2 are correct.
  • Option 3 is wrong: B is a girl and fails the first decision.
  • Option 4: scores above 50 are 70, 55, 80, giving 205, so it is correct.
  • Answer: options 1, 2 and 4.
Revision overview
The problemSum of Boys' Maths marks only
Not every card should be added
Where the filter goesAfter: Pick, Move X to Pile 2
Before: add to Sum
Decision: X is a boy?
Decision outcomesYes (True): add Maths score
No (False): do nothing
Sum with filteringLecture 1.5
Boys and girls togetherTwo sums: BoySum, GirlSum
Yes: BoySum · No: GirlSum
Loop backBoth paths return to the
same place in the iteration
InitialisationEvery sum starts at 0
(Sum, or BoySum and GirlSum)
Revision: everything in Lecture 1.5 on one page
Next · Lecture 1.7Introduction to Datatypes
03
Lecture 1.7

Introduction to Datatypes

Our data set is organised into cards, and each card stores one data item. Each card has several elements. Before we compute with them we need to be sure the data is sane.

3.1Sanity of data: what we observed

Each card has elements such as numbers (e.g. marks) and sequences of characters (e.g. name, bill item, word). We noticed two kinds of restriction.

Restrictions on values
  • Marks have to lie between 0 and 100.
  • A name cannot have funny characters.
Constraints on operations
  • Addition of marks is possible, but multiplication of marks does not make sense.
  • Comparing one name with another gives a Boolean (True or False), but we cannot add a name to another.

3.2What is a data type?

Definition: data type

A Data Type (or simply Type) tells the computer, or another person, how we intend to use a data element. Specifying that a variable has a type describes the constraints on it: the values it can store and the operations permitted on it.

Question 1

What are the values (or range of values) the element can take?

Question 2

What are the operations that can be performed on the data element?

3.3Basic data types

Three basic types are needed for our data sets. Each is described by its values and its operations, along with the type each operation produces.

Basic data type
Boolean

Values: only two: True, False

OperationResult type
AND, ORBoolean
Basic data type
Integer

Values: … −3, −2, −1, 0, 1, 2, 3 …

OperationResult type
+, −, ×, ÷Integer
<, >, =Boolean
Basic data type
Character

Values: alphanumeric A…Z, a…z, 0…9 and special characters . , ; : * / & % $ # @ ! …

OperationResult type
=Boolean
String (a sequence of characters) is the fourth basic type; it is introduced with its subtypes in Lecture 1.8. NOT is the usual third Boolean operation; the lecture slides list only AND and OR.

3.4Integer division

Division ÷ needs care, because an Integer operation must give an Integer back. There are two ways to handle it:

Option 1
Exact only

The first number has to be divisible by the second.

21 ÷ 7 = 3

Option 2
Change the definition

Take only the quotient and drop the remainder.

22 ÷ 7 = 3

Result types

AND, OR on Booleans give a Boolean. + − × ÷ on Integers give an Integer. Comparisons < > = on Integers give a Boolean, and so does = on Characters.

Example 7Result type of an expression

Give the type of each result. (a) True AND False (b) 7 + 5 (c) 7 < 5 (d) 'a' = 'b' (e) (7 < 5) OR (2 = 2).

Solution
  • (a) Boolean (value False).
  • (b) Integer (value 12).
  • (c) Boolean: a comparison of Integers gives a Boolean (value False).
  • (d) Boolean: = on Characters gives a Boolean (value False).
  • (e) Boolean: each comparison is a Boolean, and OR of two Booleans is a Boolean (value True).
Example 8Integer division

Evaluate with Option 2 (quotient only): (a) 22 ÷ 7 (b) 9 ÷ 2 (c) 5 ÷ 8. Which of these would be allowed under Option 1?

Solution
  • (a) 22 ÷ 7 = 3 (since 22 = 7 × 3 + 1; the remainder 1 is dropped).
  • (b) 9 ÷ 2 = 4 (9 = 2 × 4 + 1).
  • (c) 5 ÷ 8 = 0 (5 = 8 × 0 + 5).
  • Under Option 1 none of them is allowed, because none is exactly divisible (21 ÷ 7 would be).

3.5Reading types like a compiler

Think of a type as a contract: it says what you may store and what you may do with it. Checking an expression means checking that contract at every step, from the inside out.

  1. Take the innermost operation first.
  2. Look at the types of its operands. Is the operation defined for them?
  3. Write down its result type from the type table.
  4. That result is now an operand of the next operation outward. Repeat until one type is left.
ExpressionStep by stepVerdict
(7 + 5) < 10Integer + Integer → Integer; Integer < Integer → Booleanvalid, Boolean
(7 < 5) AND (2 = 2)Boolean; Boolean; Boolean AND Boolean → Booleanvalid, Boolean
(7 < 5) + 17 < 5 is Boolean; Boolean + Integer is not definedinvalid
7 AND 5AND needs Booleans, these are Integersinvalid
Only three patterns

Arithmetic keeps the type (Integer → Integer). Comparisons and = always give Boolean. AND, OR need Boolean on both sides, so to combine tests you must compare first: (a < b) AND (c = d).

Character is not Integer, and not String

  • A Character is a single symbol and has only =. A String is a sequence of characters and has char in string? and =.
  • A digit written as a character, like '7', is a Character, not the Integer 7. '7' = '7' is fine (Boolean) but '7' + '2' is not defined.

3.6Exam tips and common mistakes

Exam tips
  • For result-type questions write the type under each operation, working from the inside out.
  • Memorise the three patterns: arithmetic keeps the type, comparison gives Boolean, AND/OR give Boolean.
  • Integer division keeps only the quotient: 22 ÷ 7 = 3, 9 ÷ 2 = 4, 5 ÷ 8 = 0.
  • When asked to define a data type, always give both parts: the values and the operations.
Common mistakes
  • Saying 7 < 5 gives an Integer (or 0/1). It gives a Boolean.
  • Using AND/OR on Integers.
  • Rounding in integer division. 9 ÷ 2 is 4, not 5, and not 4.5.
  • Treating digit characters as numbers.
  • Defining a type by its values only and forgetting the operations.

Practice questions (graded-assignment style)

Q1Result type

Multiple Choice Question (MCQ): choose the one correct option.

What is the type of the result of (4 < 9) AND (3 = 3)?

1
Integer
2
Boolean
3
Character
4
Not defined
Solution
Idea

Comparisons give Boolean. AND of two Booleans gives Boolean.

  • 4 < 9 is a Boolean (True) and 3 = 3 is a Boolean (True).
  • True AND True is a Boolean. The value is True.
  • Answer: option 2.
Q2Spot the invalid expression

Multiple Choice Question (MCQ): choose the one correct option.

Which expression is not valid?

1
(2 + 3) < 6
2
(2 < 3) + 1
3
(2 < 3) OR (4 = 4)
4
7 ÷ 2 = 3
Solution
Idea

Work from the inside out and check that each operation is defined for the types it receives.

  • Option 1: Integer + Integer gives Integer, then Integer < Integer gives Boolean. Valid.
  • Option 2: 2 < 3 is Boolean, and Boolean + Integer is not defined. Invalid.
  • Option 3: Boolean OR Boolean gives Boolean. Valid.
  • Option 4: 7 ÷ 2 is 3 (quotient only), then 3 = 3 is Boolean. Valid.
  • Answer: option 2.
Q3Integer division

Numerical Answer Type (NAT).

With integer division (quotient only, remainder dropped), what is 47 ÷ 6?

Solution
Idea

Find how many whole times 6 fits into 47.

  • 6 × 7 = 42 and 6 × 8 = 48, which is more than 47.
  • 47 = 6 × 7 + 5. The quotient is 7 and the remainder 5 is dropped.
  • Answer: 7
Q4The Character type

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements about the Character type.

1
Its values include letters, digits and special characters.
2
The operation + is defined on it.
3
The operation = gives a Boolean.
4
'7' is the Integer 7.
Solution
Idea

A Character is a single symbol and its only operation here is equality.

  • Option 1 is correct.
  • Option 2 is wrong: Character has only =.
  • Option 3 is correct.
  • Option 4 is wrong: '7' is a Character that looks like a digit, not an Integer.
  • Answer: options 1 and 3.
Revision overview
Values + operationsMarks must lie in 0 to 100
Names: no funny characters
Tells how data will be used
Why types?Constraints on operations
Add marks: fine, multiply: no
Compare names: gives Boolean
Add two names: not allowed
BooleanValues: True, False
AND, OR give Boolean
Data TypeLecture 1.7
Integer… −3, −2, −1, 0, 1, 2, 3 …
+ − × ÷ give Integer
< > = give Boolean
Integer division21 ÷ 7 = 3 (divisible)
22 ÷ 7 = 3 (drop the remainder)
CharacterA-Z, a-z, 0-9 and symbols
= gives Boolean
Revision: everything in Lecture 1.7 on one page
Next · Lecture 1.8Subtypes of Basic Datatypes
04
Lecture 1.8

Subtypes of Basic Datatypes

A basic type is often too loose for a particular piece of data. A subtype restricts the values and/or operations of a basic type so that it fits one purpose.

4.1Subtypes of Integer

A basic type is often too loose for a particular piece of data. A subtype takes a basic type and restricts its values and/or its operations so that it fits one purpose.

Idea

Integer allows every whole number and all of + − × ÷ < > =. A subtype such as Marks keeps only the values 0 to 100 and only the operations that make sense for marks.

Integer… −3, −2, −1, 0, 1, 2, 3 …←→Count0, 1, 2, 3, …→SeqNo0, 1, …, MaxMarks0, 1, …, 1000Each Integer subtype is a restricted range (not to scale)
Figure 6. Each Integer subtype is a restricted range (not to scale)
Subtype of Integer
SeqNo

Values: 0, 1, 2, …, Max. Max can be some reasonable number, e.g. 10000, the largest data set size we can handle.

Operations: none of the Integer operations make sense for SeqNo.

Subtype of Integer
Marks

Values: 0, 1, 2, 3, …, 100

OperationResult type
+, −Marks
<, >, =Boolean

×, ÷ do not make sense for marks.

Subtype of Integer
Count

Values: 0, 1, 2, 3, …

OperationResult type
+, −Count
<, >, =Boolean

×, ÷ do not make sense for counts.

Note. Adding or subtracting two Marks gives a Marks value, not a plain Integer. The result stays inside the subtype. Comparisons give a Boolean, just as for Integer.
A caution. The slides treat + and − on Marks as giving Marks, assuming the answer stays in range. In practice 70 + 60 = 130 is outside 0 … 100 and 30 − 50 is below 0, so a program must guard such cases. This is exactly why a total of marks gets its own, wider type (TMarks, up to 300) in Lecture 1.10. The same caution applies to Count (subtracting a bigger count gives a negative number).

4.2Subtype of Character

Parent type: Character

Values: A … Z, a … z, 0 … 9 and special characters.

Operation: = gives a Boolean.

Subtype of Character
Gender

Values: M or F

OperationResult type
=Boolean

Gender narrows all of that down to just two values.

4.3String and its subtypes

The String type holds any sequence of characters.

Basic data type
String

Values: any sequence of characters

OperationResult type
char in string?Boolean
=Boolean
and other string operations …
Subtype of String
Names

Values: strings with only alphabet characters

OperationResult type
=Boolean
Subtype of String
City

Values: strings with only alphabet characters

OperationResult type
=Boolean
Subtype of String
Words

Values: strings with alphanumeric characters and . , ; : …

OperationResult type
=Boolean
Subtype of String
Category

Values: can take only one of "Noun", "Verb", "Pronoun", "Adjective" …

OperationResult type
=Boolean
Updated in the slides (differs from the video). String is made more restrictive for Names and City (alphabet characters only), and the operation = is added for Names, City, Words and Category. (Strictly, a name such as "Mary Ann" has a space, so a real system would allow that too; the slides keep the definition simple.)
Example 9Pick the right type

Choose the most suitable type for each data element: a student's marks out of 100; the position of a card in the data set; the number of items on a bill; gender; a city name; a word from a paragraph (it may have punctuation); the grammatical class of a word.

Solution
Data elementTypeWhy
Marks out of 100Marksvalues 0 to 100
Position of a cardSeqNo0, 1, …, Max; no arithmetic
Number of itemsCount0, 1, 2, …; + and − allowed
GenderGenderonly M or F
City nameCityalphabet characters only
Word from a paragraphWordsalphanumeric and . , ; :
Grammatical classCategoryone of Noun, Verb, Pronoun, …
Example 10Is the expression allowed?

For each expression say whether it is allowed, and the result type if it is: Marks + Marks, Marks × Marks, Marks < Marks, SeqNo + SeqNo, Count − Count, Gender = Gender, Names + Names.

Solution
ExpressionAllowed?Result type
Marks + MarksYesMarks
Marks × MarksNo—
Marks < MarksYesBoolean
SeqNo + SeqNoNo—
Count − CountYesCount
Gender = GenderYesBoolean
Names + NamesNo—

4.4Choosing the right subtype

To pick a subtype, ask three questions in this order:

  1. Which values are allowed? A range (0 to 100), two letters only (M or F), only alphabets, or one word out of a fixed list.
  2. Does arithmetic make sense? Adding marks: yes. Adding sequence numbers: no.
  3. If no arithmetic, is comparing for equality enough? Then the type has only =.

Look-alikes, and how to tell them apart

SeqNo vs Count

Both are whole numbers from 0. SeqNo is a label (position of a card, like a roll number), so adding two is meaningless. Count is a quantity (how many), so + and − make sense.

Marks vs Count

Both allow + and −. The difference is the range: Marks stops at 100, Count has no fixed upper limit.

Gender and Category

These are fixed lists. Gender allows only M or F. Category allows only words like Noun, Verb, Pronoun, Adjective.

Names vs Words

Names (and City) allow only alphabets. Words also allow digits and punctuation . , ; :, because words in a paragraph carry commas and full stops.

10-second answer table

SubtypeOfAllowed operationsResult type
SeqNoIntegernone—
MarksInteger+ −, < > =Marks, Boolean
CountInteger+ −, < > =Count, Boolean
GenderCharacter=Boolean
Names, City, Words, CategoryString=Boolean

Never allowed: × ÷ on Marks or Count, any arithmetic on SeqNo, and + on strings.

4.5Exam tips and common mistakes

Exam tips
  • Match the clue words in the question to a subtype: "out of 100" → Marks, "position" → SeqNo, "how many" → Count, "M or F" → Gender, "only letters" → Names or City, "punctuation" → Words, "one of a fixed list" → Category.
  • For "is this allowed?" look the operation up in the table first, then give the result type.
  • Mention the parent type: Marks is a subtype of Integer, Gender of Character, Names of String.
Common mistakes
  • Doing arithmetic on SeqNo.
  • Saying Marks × Marks is allowed or gives Marks.
  • Forgetting that a comparison gives a Boolean even for subtypes: Marks < Marks is Boolean, not Marks.
  • Using Marks for a total of several subjects (it can go past 100; Lecture 1.10 uses TMarks).

Practice questions (graded-assignment style)

Q1Pick the subtype

Multiple Choice Question (MCQ): choose the one correct option.

The position of a card in the data set needs a type on which no arithmetic makes sense. Which subtype fits?

1
Marks
2
Count
3
SeqNo
4
Gender
Solution
Idea

A position is a label, not a quantity.

  • SeqNo: values 0 to Max, and none of the Integer operations make sense.
  • Marks and Count allow + and −.
  • Gender is a Character subtype with only M or F.
  • Answer: option 3.
Q2Allowed expressions

Multiple Select Question (MSQ): select all that apply.

Which expressions are allowed?

1
Marks + Marks
2
Marks × Marks
3
Count − Count
4
Names + Names
5
Gender = Gender
Solution
Idea

Marks and Count keep + and −. Strings and Gender have only equality.

  • Option 1: allowed, result is Marks.
  • Option 2: not allowed, multiplication of marks makes no sense.
  • Option 3: allowed, result is Count.
  • Option 4: not allowed, strings have only =.
  • Option 5: allowed, result is Boolean.
  • Answer: options 1, 3 and 5.
Q3Find the invalid value

Multiple Choice Question (MCQ): choose the one correct option.

Which value is not valid for its subtype?

1
100 as Marks
2
"Chennai" as City
3
'F' as Gender
4
"Chennai3" as City
Solution
Idea

Check the allowed values of each subtype.

  • Option 1: Marks go from 0 to 100, so 100 is valid.
  • Option 2: only alphabets, valid.
  • Option 3: Gender is M or F, valid.
  • Option 4: City allows only alphabets and 3 is a digit, so invalid.
  • Answer: option 4.
Revision overview
Integer+ − × ÷ give Integer
< > = give Boolean
SeqNo0, 1, …, Max (e.g. 10000)
No integer operations apply
Marks · CountMarks 0 to 100; Count 0, 1, 2, …
+ − give the same type
< > = give Boolean
Subtypes of basic typesLecture 1.8
Character · GenderA-Z, a-z, 0-9, symbols; = gives Boolean
Gender: M or F
StringAny sequence of characters
char in string?, = give Boolean
String subtypesNames, City: alphabet only
Words: alphanumeric and . , ; :
Category: one of Noun, Verb, …
Revision: every subtype from Lecture 1.8, with its values and operations
Next · Lecture 1.9Transformation of Sub-datatypes
05
Lecture 1.9

Transformation of Sub-datatypes

Some data does not look like an Integer, yet we can still model it as one. We transform the value into an integer for storage and calculation, and transform it back when we print it.

5.1Dates: a subtype of Integer

Store a date as the day number within the year: 0 for 1 Jan, 1 for 2 Jan, …, 30 for 31 Jan, 31 for 1 Feb, and so on.

Subtype of Integer
Dates

Values: 0, 1, 2, 3, …, 365

OperationResult type
printString
<, >, =Boolean
The print operation

Turns the stored number into readable text:

print(0) = "1 Jan"

print(31) = "1 Feb"

Comparing two Dates (< > =) works on the stored numbers and gives a Boolean.

STORED (Dates value)0"1 Jan"1"2 Jan"…30"31 Jan"31"1 Feb"365print(Dates) gives a String
Figure 7. A date is stored as a day number and shown with print
Why 365? Values 0 … 365 are 366 days, which fits a leap year (31 Dec is day 365). In an ordinary year the last day number is 364.

5.2Fractional marks: what about 62.5?

Marks were whole numbers from 0 to 100, but real marks can be fractional, e.g. 62.5. There are two ways to deal with that.

Option 1
Use Float

Use another basic type for real numbers, called Float. But our values have at most 2 decimal places (e.g. 75.25), so we would have to write extra constraints for the float values.

Option 2
Multiply by 100

A fractional number with at most 2 decimal places becomes an integer. We compute on the integers, remembering they are scaled by 100, and when we print we scale the number back down.

5.3Scaled subtypes of Integer

The lecture applies the ×100 idea to marks, to shopping bill amounts and to bill quantities.

Fractional marks
Marks

Values: 0, 1, 2, 3, …, 10000
Stored as: 62.5 is stored as 6250; print(6250) = "62.5"

OperationResult type
printString
+, −Marks
<, >, =Boolean
Bill price / total
Amount

Values: 0, 1, 2, 3, …
Stored as: 27.50 is stored as 2750; print(2750) = "Rs. 27.50"

OperationResult type
printString
+, −Amount
<, >, =Boolean
Bill quantity
Quantity

Values: 0, 1, 2, 3, …
Stored as: 1.25 is stored as 125; print(125) = "1.25"

OperationResult type
printString
+, −Quantity
<, >, =Boolean
Note. The range of Marks is 0 … 10000 (62.5 is stored as 6250, and 100 marks is 10000). The slide corrects the range shown in the video. This scaled Marks is a different subtype from the whole-number Marks of Lecture 1.8 (0 … 100).
REAL VALUESTORED VALUEPRINTED OUTPUTMarks62.5× 1006250print"62.5"at most 2 decimalsstored as an integera StringAmount27.50× 1002750print"Rs. 27.50"at most 2 decimalsstored as an integera StringQuantity1.25× 100125print"1.25"at most 2 decimalsstored as an integera StringScale up to store, compute on integers, scale down to print
Figure 8. Scale up to store, compute on integers, scale down to print
Example 11Add fractional marks

Add 62.5 and 17.25 marks.

Solution
  • Stored values: 6250 + 1725 = 7975, a Marks value.
  • Printing scales it back down: print(7975) gives "79.75".
  • Check: 62.5 + 17.25 = 79.75 ✓.
Example 12Add two bill amounts

A bill has two items costing Rs. 27.50 and Rs. 12.75. Find the total using the Amount type.

Solution
  • Stored: 27.50 → 2750 and 12.75 → 1275.
  • Add the integers: 2750 + 1275 = 4025, an Amount.
  • print(4025) = "Rs. 40.25".
Example 13Storing a date

Taking a leap year (days 0 … 365), what number stores 6 Dec? (The marks card in Lecture 1.10 has a date of birth of 6 Dec.)

Solution
  • Days before 1 Dec = Jan 31 + Feb 29 + Mar 31 + Apr 30 + May 31 + Jun 30 + Jul 31 + Aug 31 + Sep 30 + Oct 31 + Nov 30 = 335.
  • So 1 Dec is stored as 335 (like 1 Jan is 0), and 6 Dec as 335 + 5 = 340.
  • print(340) = "6 Dec". (In a non-leap year it would be 339.)

5.4Why scale by 100, and how to convert

Every value here has two faces: the stored value (an integer the program computes with) and the printed value (text a person reads). The operation print turns the first into the second.

Why integers?

  • Computers keep Float values in binary, and many decimals (like 0.1) cannot be stored exactly, so tiny errors creep into totals. Integers are exact.
  • With at most 2 decimal places, multiplying by 100 gives an exact integer, so nothing is lost.
  • Only + − are offered. Adding two scaled values keeps the same scale (6250 + 1725 is still "hundredths"). Multiplying two scaled values would give a scale of 100 × 100 and no longer mean the same thing, so × and ÷ are not defined.
Conversion rule

stored = value × 100, and printed = stored ÷ 100 shown with 2 decimals (Amount adds Rs.).

Real valueStoredPrinted
62.5 marks6250"62.5"
100 marks (maximum)10000"100"
Rs. 27.502750"Rs. 27.50"
Rs. 0.055"Rs. 0.05"
1.25 kg125"1.25"

Day number of a date

stored = (days before the 1st of that month) + (day − 1). So 1 Jan is 0. Use this table of day numbers for the 1st of each month:

DateLeap yearNon-leap year
1 Jan00
1 Feb3131
1 Mar6059
1 Apr9190
1 May121120
1 Jun152151
1 Jul182181
1 Aug213212
1 Sep244243
1 Oct274273
1 Nov305304
1 Dec335334

Example: 25 Dec is 335 + 24 = 359 in a leap year and 334 + 24 = 358 otherwise.

5.5Exam tips and common mistakes

Exam tips
  • Three words: scale up, compute, scale down.
  • Read what is asked: the stored value or the printed value.
  • Self-check a scaled answer by dividing it by 100 and comparing with the decimal calculation.
  • For dates, count whole months before it, then add (day − 1). Say whether you assumed a leap year.
Common mistakes
  • Multiplying by 10 instead of 100 (62.5 → 625 is wrong, it is 6250).
  • Losing the trailing zero: 27.50 → 275 is wrong, it is 2750.
  • Printing the stored number directly (6250 instead of 62.5).
  • Counting dates from 1, so that 1 Jan = 1. Here 1 Jan = 0.
  • Mixing the whole-number Marks (0 to 100) with the scaled Marks (0 to 10000).

Practice questions (graded-assignment style)

Q1Scaled addition

Numerical Answer Type (NAT).

Using the scaled Marks type (value × 100), add 45.75 and 30.5 marks. What is the stored value of the result?

Solution
Idea

Scale up, add the integers, and only scale down when printing.

  • 45.75 is stored as 4575 and 30.5 as 3050.
  • 4575 + 3050 = 7625.
  • print(7625) shows "76.25", which matches 45.75 + 30.5.
  • Answer: 7625
Q2Date number

Numerical Answer Type (NAT).

In a leap year 1 Dec is stored as 335 and 1 Jan as 0. What number stores 25 Dec?

Solution
Idea

Stored value = number for the 1st of the month + (day − 1).

  • 25 Dec is 24 days after 1 Dec.
  • 335 + 24 = 359.
  • Answer: 359
Q3Print an Amount

Multiple Choice Question (MCQ): choose the one correct option.

An Amount is stored as 2505. What does print show?

1
"Rs. 2505"
2
"Rs. 250.5"
3
"Rs. 25.05"
4
"Rs. 2.505"
Solution
Idea

print divides the stored value by 100 and adds Rs.

  • 2505 ÷ 100 = 25.05.
  • So the printed text is "Rs. 25.05".
  • Answer: option 3.
Q4Why scale by 100?

Multiple Select Question (MSQ): select all that apply.

Choose the correct reasons and facts about scaling by 100.

1
Integers are exact, so there are no rounding errors.
2
Only + and − keep the scale, so × and ÷ are not offered.
3
print scales the number back down.
4
Scaled Marks has the range 0 to 1000.
Solution
Idea

Store as an integer, compute on integers, and convert only for display.

  • Option 1 is correct: many decimals cannot be stored exactly as a Float.
  • Option 2 is correct: multiplying two scaled values changes the scale.
  • Option 3 is correct.
  • Option 4 is wrong: 100 marks × 100 = 10000, so the range is 0 to 10000.
  • Answer: options 1, 2 and 3.
Revision overview
Store as integersDates: subtype of Integer, 0 to 365
0 = 1 Jan, 31 = 1 Feb
print gives a String
Marks (fractional)62.5 is stored as 6250
Range: 0 to 10000
print(6250) = "62.5"
Amount27.50 is stored as 2750
print(2750) = "Rs. 27.50"
Transforming valuesLecture 1.9
Quantity1.25 is stored as 125
print(125) = "1.25"
Why scale by 100?Float needs extra constraints
At most 2 decimals: exact integer
The methodScale up, compute, scale down
Operations: print, + −, < > =
Revision: everything in Lecture 1.9 on one page
Next · Lecture 1.10Introduction to Complex Datatypes
06
Lecture 1.10

Introduction to Complex Datatypes

Basic types and subtypes describe a single value. A card holds many values together, and a data set holds many cards. For these we need Records and Lists.

6.1Record (also called struct or tuple)

Definition: record

A Record is a data type with multiple fields, each of which has a name and a value. The type of each field is a data type we already defined, so the sanity of the field values is ensured by the data type specifications.

MarksCard

Name of fieldType of fieldExample value
sequence no:SeqNo9
name:NamesClarence
gender:GenderM
date of birth:Dates6 Dec
city:CityBengaluru
mathsMarks:Marks63
physicsMarks:Marks88
chemistryMarks:Marks73
totalMarks:TMarks224
Note. TMarks is the same as Marks, except its range goes up to 300 (the slide corrects the video). The example values are from the marks card shown in the lecture.

WordInPara

Name of fieldType of field
sequence no:SeqNo
word:Words
category:Category
letterCount:Count

6.2List

Definition: list

A List is a sequence of data elements, for example a sequence of records. The elements are usually all of the same data type.

  • MarksCardList: the data type for our data set of all marks cards. Each element is a MarksCard record.
  • ParagraphWordList: the data type for our word data set. Each element is a WordInPara record.
  • ShoppingBillList: the data type for the shopping bill data set. For this we first define the Record data type for a shopping bill.
MarksCardListMarksCardelement 1MarksCardelement 2MarksCardelement 3MarksCardelement 4…ParagraphWordListWordInParaelement 1WordInParaelement 2WordInParaelement 3WordInParaelement 4…ShoppingBillListShoppingBillelement 1ShoppingBillelement 2ShoppingBillelement 3ShoppingBillelement 4…A List is a sequence of records
Figure 9. A List is a sequence of records

6.3Record for a shopping bill

A shopping bill has a store name, a customer name, a total, and a list of items. So the field items cannot be a simple type: each item is itself a record, and items is a List of those records.

ShoppingBill
Record
Name of fieldType
sequence no:SeqNo
storeName:Name
customerName:Name
items:ItemList
totalBillValue:Amount
Item
Record
Name of fieldType
itemName:Name
itemCategory:String
quantity:Quantity
unitPrice:Amount
cost:Amount

ItemList is a List of the Item data type. (In these slides Name is the same kind of value as the Names subtype.)

ShoppingBill (Record)sequence no:SeqNostoreName:NamecustomerName:Nameitems:ItemListtotalBillValue:AmountItem (Record)itemName:NameitemCategory:Stringquantity:QuantityunitPrice:Amountcost:AmountItemLista List ofA Record can contain a List of other records
Figure 10. A record can contain a List of other records

6.4Summary

  • A data type defines the values a variable can take and the operations permitted on it.
  • Basic data types needed for our data sets: Integer, Boolean and Character.
  • Subtypes further restrict the values and/or operations allowed.
  • A Record is a collection of named fields, each with the same or different data types.
  • A List is a sequence of items, all usually of the same data type.
Example 14Why is totalMarks a TMarks?

In the marks card, why is totalMarks of type TMarks and not Marks?

Solution
  • The three subject marks are each in 0 … 100, but their total can reach 300. For the card above, 63 + 88 + 73 = 224, which is outside the range of Marks.
  • So the total needs its own type: the same as Marks but with range 0 … 300.
Example 15Record or List?

Decide whether each is best modelled as a Record or a List: (a) all the students' marks cards; (b) one student's marks card; (c) the items bought on one bill; (d) one item on a bill; (e) the words of a paragraph.

Solution
ItemModelWhy
All marks cardsList (MarksCardList)a sequence of MarksCard records
One marks cardRecord (MarksCard)named fields of different types
Items on one billList (ItemList)a sequence of Item records
One itemRecord (Item)name, category, quantity, price, cost
Words of a paragraphList (ParagraphWordList)a sequence of WordInPara records

6.5Putting it together: from one value to a whole data set

Week 1 builds data types in four levels. Each level is made from the one before it.

LevelDescribesExample
Basic typeone simple valueInteger, Boolean
Subtypeone value, with restrictionsMarks, Gender
Recordone card: several named fields, types can differMarksCard
Listmany items, usually all of the same typeMarksCardList
Record

Think one thing, many attributes. Fields have names and can have different types. Size is fixed by the definition.

List

Think many things, one kind. Elements usually share one type. Size can grow with the data.

This links back to the flowcharts

Pile 1 is really a List (MarksCardList). Card X is a Record (MarksCard). CardX's Maths score is one field of that record, and X is a boy? tests the gender field (Gender, whose = gives a Boolean). So the first two lectures use exactly the types of the last two.

How to design a record in the exam

  1. List every piece of information the card holds.
  2. Give each one the most specific type (Names rather than String, Count rather than Integer).
  3. Write the field names and types in a table (add an example value if asked).
  4. If a field holds many entries of one kind (like the items on a bill), define a separate Record for one entry and make the field a List of it.

6.6Exam tips and common mistakes

Exam tips
  • Answer "define a data type for ..." questions with a field table: field name, type, example.
  • Use a subtype for every field whenever one fits.
  • Totals of three subjects (each up to 100) use TMarks, range 0 to 300.
  • Name a list type by its element: Item → ItemList, MarksCard → MarksCardList.
Common mistakes
  • Typing totalMarks as Marks. A total of 224 is out of range.
  • Using a List where one Record is meant (or the reverse).
  • Storing a bill's items as a single String instead of an ItemList.
  • Using plain String or Integer where a subtype exists.

Practice questions (graded-assignment style)

Q1Total of three subjects

Multiple Choice Question (MCQ): choose the one correct option.

Each of three subjects is marked out of 100. Which type should hold the total?

1
Marks
2
TMarks
3
Count
4
SeqNo
Solution
Idea

The total can go past the range of Marks.

  • A total can reach 300, which is outside Marks (0 to 100).
  • TMarks is Marks with range 0 to 300.
  • Answer: option 2.
Q2Which field is a List?

Multiple Choice Question (MCQ): choose the one correct option.

In the ShoppingBill record, which field holds a List?

1
storeName
2
items
3
totalBillValue
4
customerName
Solution
Idea

A field that holds many entries of one kind is a List of a record.

  • items has type ItemList, a List of Item records.
  • The other three are single values: Name, Amount and Name.
  • Answer: option 2.
Q3Record and List

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements.

1
A Record has named fields, and the fields may have different types.
2
The elements of a List usually have the same type.
3
A Record can contain a List.
4
A List cannot contain Records.
Solution
Idea

Record means one thing with many attributes. List means many things of one kind.

  • Options 1, 2 and 3 are correct.
  • Option 4 is wrong: MarksCardList is a List of MarksCard records.
  • Answer: options 1, 2 and 3.
Q4Fields in MarksCard

Numerical Answer Type (NAT).

How many fields does the MarksCard record have?

Solution
Idea

Count the rows of the field table.

  • sequence no, name, gender, date of birth, city, mathsMarks, physicsMarks, chemistryMarks, totalMarks.
  • That is 9 fields.
  • Answer: 9
Revision overview
Data TypesBasic typesComplex typesBooleanIntegerCharacterStringno subtypesin these lecturesSeqNoMarksCountDatesAmountQuantityGenderNamesCityWordsCategoryRecordListMarksCardWordInParaShoppingBillItemMarksCardListParagraphWordListShoppingBillListItemList
Figure 11. The full map of data types from Week 1
Next · All lecturesWeek 1 Summary Sheet
07
All lectures

Week 1 Summary Sheet

Everything from Week 1 on one sheet. Use it for a last-minute revision.

Flowcharts

Flowchart symbols
  • Terminal: Start or End
  • Process: changes the value of variables
  • Flowline: order of execution
  • Decision: picks the path, Yes (True) or No (False)
Iteration pattern
  • Initialise variables (Count = 0, Sum = 0)
  • Ask: unvisited elements? No: End
  • Yes: pick an element, mark it visited (move to Pile 2), update variables
  • Go back to the start of the iteration
Filtering
  • Put the decision inside the iteration, e.g. X is a boy?
  • Yes: update that sum. No: skip, or update the other sum
  • Both paths return to the same place in the loop
  • One variable per group: BoySum, GirlSum
What a data type is
  • The values a variable can take
  • The operations allowed on it
  • Basic types: Boolean, Integer, Character (and String)
  • Subtypes restrict values and/or operations

Basic types

TypeValuesOperations and result type
BooleanTrue, FalseAND, OR give Boolean
Integer… −2, −1, 0, 1, 2 …+ − × ÷ give Integer (22 ÷ 7 = 3); < > = give Boolean
CharacterA-Z, a-z, 0-9, special characters= gives Boolean
StringAny sequence of characterschar in string?, = give Boolean

Subtypes

SubtypeOfValuesOperations
SeqNoInteger0 … Maxnone make sense
MarksInteger0 … 100 (or 0 … 10000 when scaled)+ − give Marks; < > = give Boolean
CountInteger0, 1, 2, …+ − give Count; < > = give Boolean
DatesInteger0 … 365print gives String; < > = give Boolean
Amount, QuantityInteger0, 1, 2, …print gives String; + − keep the type; < > = give Boolean
GenderCharacterM or F= gives Boolean
Names, CityStringonly alphabet characters= gives Boolean
WordsStringalphanumeric and . , ; : …= gives Boolean
CategoryStringone of Noun, Verb, Pronoun, Adjective, …= gives Boolean

Transforming values and complex types

Transforming values
  • Dates: day number, print(0) = "1 Jan", print(31) = "1 Feb"
  • Multiply by 100 to store fractions: 62.5 → 6250, 27.50 → 2750, 1.25 → 125
  • Compute on integers, scale down in print
Complex types
  • Record: named fields, each with a type (MarksCard, WordInPara, ShoppingBill, Item)
  • List: a sequence of items, usually of one type (MarksCardList, ParagraphWordList, ShoppingBillList, ItemList)
  • A Record can hold a List of Records (items: ItemList)

Exam tips: last-minute checklist

Do
  • Initialise before the loop; loop back to the decision
  • Move X to Pile 2 on every path
  • n cards: decision n + 1 times, body n times
  • Arithmetic keeps the type; comparison gives Boolean
  • × 100 to store, ÷ 100 to print
  • 1 Jan is day 0
  • Totals of three subjects: TMarks
Do not
  • Initialise inside the loop
  • Do arithmetic on SeqNo
  • Use × or ÷ on Marks or Count
  • Use AND/OR on non-Booleans
  • Treat digit characters as numbers
  • Use Float for 2-decimal values
  • Send a No branch to End before the pile is empty

Numbers worth remembering

FactValue
Maximum of whole-number Marks100
Maximum of TMarks (3 subjects)300
Maximum of scaled Marks10000
Scale factor for 2 decimals× 100
Dates range (leap year)0 … 365
1 Dec in a leap year335
Integer division22 ÷ 7 = 3
Back to top