Computational
Thinking 1
Flowcharts, iteration with filtering, and the data types that keep our data sane. Lectures 1.4 to 1.10.
Chapters
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
Start / End
Indicates the start or end of the program.
Process or activity
A set of operations that change the value of data (variables), like Sum = 0.
Flowline or arrow
Shows the order of execution of the program steps.
Decision
Determines which path the program will take, e.g. X is a boy?.
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.
- Start. The cards are all assumed to be in Pile 1.
- Initialise the variable
count = 0. - 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. - 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?"
- No (False): no more cards, so the program can End. The variable
countcarries the required value. - Yes (True): pick a card from Pile 1 and call it
X. - Move X to Pile 2 so that we never visit card X again.
- Increment count, then go back to the beginning of the iteration (the decision box).
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 = 0instead ofcount = 0. - Replace Increment count with Add CardX's Maths score to Sum.
The rest of the flowchart remains the same.
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.
| Generic step | Counting cards | Sum of Maths marks |
|---|---|---|
| Initialise | Count = 0 | Sum = 0 |
| Unvisited elements? | More cards in Pile 1? | More cards in Pile 1? |
| Pick an unvisited element | Pick a card X from Pile 1 | Pick a card X from Pile 1 |
| Mark element as visited | Move X to Pile 2 | Move X to Pile 2 |
| Update variables | Increment count | Add CardX's Maths score to Sum |
Pile 1 has 3 cards: A, B, C. Trace the counting flowchart and write the value of count after each pass.
| Pass | More cards in Pile 1? | Card picked | count |
|---|---|---|---|
| — | start: all in Pile 1 | — | 0 |
| 1 | Yes | A → Pile 2 | 1 |
| 2 | Yes | B → Pile 2 | 2 |
| 3 | Yes | C → Pile 2 | 3 |
| check | No | — | End, count = 3 |
The decision is asked one more time than there are cards: 3 Yes answers and a final No.
Three cards have Maths scores 40, 70 and 55. Trace the sum flowchart.
| Pass | Card X | Maths score | Sum |
|---|---|---|---|
| — | — | — | 0 |
| 1 | A | 40 | 0 + 40 = 40 |
| 2 | B | 70 | 40 + 70 = 110 |
| 3 | C | 55 | 110 + 55 = 165 |
When Pile 1 is empty the program ends with Sum = 165.
Suppose we forget the step Move X to Pile 2. What goes wrong?
- 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.
- 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
countstays0, which is the correct answer. - 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.
- Initialise outside the loop.
count = 0must run once. If it sat inside the loop it would reset to 0 on every pass and the answer would be wrong. - 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?
| Box | Runs | Why |
|---|---|---|
| Start, initialise, End | 1 | once per program |
| More cards in Pile 1? | n + 1 | n times Yes, then one final No |
| Pick X, Move X to Pile 2, update variable | n | only on the Yes path, once per card |
1.6Exam tips and common mistakes
- 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.
- Writing
Sum = 0inside 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)
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?
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.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements about an iteration flowchart.
Sum are initialised before the loop.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.
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?
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 = 0before the loop. - Answer: 35
Process: changes data
Decision: picks the path
Flowline: order of steps
Pick card, move to Pile 2
Increment count
Stop when Pile 1 is empty
Add Maths score of X to Sum
Rest of flowchart is the same
Unvisited elements?
Pick, mark visited, update
No (False): go to End
to the start of the iteration
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:
- After Move X to Pile 2, we have to do something before we add to
Sum. - We check if X is a boy. This is a new decision box.
- Yes (True): add CardX's Maths score to
Sum. - No (False): nothing to be done if X is a girl, so we simply go back 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.
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.
| Flowchart | Variables | Yes (True) | No (False) |
|---|---|---|---|
| Boys' marks only | Sum | Add Maths score to Sum | Do nothing |
| Boys and girls | BoySum, GirlSum | Add Maths score to BoySum | Add Maths score to GirlSum |
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.
| Card | X is a boy? | Action | Sum |
|---|---|---|---|
| — | — | initialise | 0 |
| A (60, M) | Yes | add 60 | 60 |
| B (75, F) | No | do nothing | 60 |
| C (50, M) | Yes | add 50 | 110 |
| D (90, F) | No | do nothing | 110 |
Final answer: Sum = 110.
Use the same four cards with the flowchart that keeps BoySum and GirlSum.
- 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.
How would you change the filtering flowchart to count the number of boys instead?
- Initialise
BoyCount = 0(instead ofSum = 0). - Keep the decision X is a boy? inside the iteration.
- On Yes (True), replace Add CardX's Maths score to Sum with Increment BoyCount.
- 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.
- 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.
- 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 + GirlSumequals the sum over all cards, and the two counts add up to n. Use this to check your answer. - 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?.
- 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?
| Question | Variables to initialise | On the Yes path |
|---|---|---|
| Sum of boys' Maths marks | Sum | add X's Maths score |
| Number of girls | GirlCount | Increment GirlCount |
| Average of boys' Maths marks | BoySum, BoyCount | add the score and increment the count |
| Boys scoring above 50 | Sum | second decision: score > 50? then add |
2.4Exam tips and common mistakes
- 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.
- 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)
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.
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
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?
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.
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.
Sum is 135.Sum would be 205.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.
Not every card should be added
Before: add to Sum
Decision: X is a boy?
No (False): do nothing
Yes: BoySum · No: GirlSum
same place in the iteration
(Sum, or BoySum and GirlSum)
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.
- Marks have to lie between
0and100. - A name cannot have funny characters.
- 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?
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.
What are the values (or range of values) the element can take?
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.
Boolean
Values: only two: True, False
| Operation | Result type |
|---|---|
AND, OR | Boolean |
Integer
Values: … −3, −2, −1, 0, 1, 2, 3 …
| Operation | Result type |
|---|---|
+, −, ×, ÷ | Integer |
<, >, = | Boolean |
Character
Values: alphanumeric A…Z, a…z, 0…9 and special characters . , ; : * / & % $ # @ ! …
| Operation | Result type |
|---|---|
= | Boolean |
3.4Integer division
Division ÷ needs care, because an Integer operation must give an Integer back. There are two ways to handle it:
Exact only
The first number has to be divisible by the second.
21 ÷ 7 = 3
Change the definition
Take only the quotient and drop the remainder.
22 ÷ 7 = 3
AND, OR on Booleans give a Boolean. + − × ÷ on Integers give an Integer. Comparisons < > = on Integers give a Boolean, and so does = on Characters.
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).
- (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 (valueFalse). - (e) Boolean: each comparison is a Boolean, and OR of two Booleans is a Boolean (value
True).
Evaluate with Option 2 (quotient only): (a) 22 ÷ 7 (b) 9 ÷ 2 (c) 5 ÷ 8. Which of these would be allowed under Option 1?
- (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 ÷ 7would 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.
- Take the innermost operation first.
- Look at the types of its operands. Is the operation defined for them?
- Write down its result type from the type table.
- That result is now an operand of the next operation outward. Repeat until one type is left.
| Expression | Step by step | Verdict |
|---|---|---|
(7 + 5) < 10 | Integer + Integer → Integer; Integer < Integer → Boolean | valid, Boolean |
(7 < 5) AND (2 = 2) | Boolean; Boolean; Boolean AND Boolean → Boolean | valid, Boolean |
(7 < 5) + 1 | 7 < 5 is Boolean; Boolean + Integer is not defined | invalid |
7 AND 5 | AND needs Booleans, these are Integers | invalid |
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
- 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.
- Saying
7 < 5gives an Integer (or 0/1). It gives a Boolean. - Using AND/OR on Integers.
- Rounding in integer division.
9 ÷ 2is 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)
Multiple Choice Question (MCQ): choose the one correct option.
What is the type of the result of (4 < 9) AND (3 = 3)?
Comparisons give Boolean. AND of two Booleans gives Boolean.
4 < 9is a Boolean (True) and3 = 3is a Boolean (True).True AND Trueis a Boolean. The value is True.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
Which expression is not valid?
(2 + 3) < 6(2 < 3) + 1(2 < 3) OR (4 = 4)7 ÷ 2 = 3Work 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 < 3is Boolean, and Boolean + Integer is not defined. Invalid. - Option 3: Boolean OR Boolean gives Boolean. Valid.
- Option 4:
7 ÷ 2is 3 (quotient only), then3 = 3is Boolean. Valid. - Answer: option 2.
Numerical Answer Type (NAT).
With integer division (quotient only, remainder dropped), what is 47 ÷ 6?
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
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements about the Character type.
+ is defined on it.= gives a Boolean.'7' is the Integer 7.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.
Names: no funny characters
Tells how data will be used
Add marks: fine, multiply: no
Compare names: gives Boolean
Add two names: not allowed
AND, OR give Boolean
+ − × ÷ give Integer
< > = give Boolean
22 ÷ 7 = 3 (drop the remainder)
= gives Boolean
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.
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.
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.
Marks
Values: 0, 1, 2, 3, …, 100
| Operation | Result type |
|---|---|
+, − | Marks |
<, >, = | Boolean |
×, ÷ do not make sense for marks.
Count
Values: 0, 1, 2, 3, …
| Operation | Result type |
|---|---|
+, − | Count |
<, >, = | Boolean |
×, ÷ do not make sense for counts.
+ 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
Values: A … Z, a … z, 0 … 9 and special characters.
Operation: = gives a Boolean.
Gender
Values: M or F
| Operation | Result 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.
String
Values: any sequence of characters
| Operation | Result type |
|---|---|
char in string? | Boolean |
= | Boolean |
and other string operations … |
Names
Values: strings with only alphabet characters
| Operation | Result type |
|---|---|
= | Boolean |
City
Values: strings with only alphabet characters
| Operation | Result type |
|---|---|
= | Boolean |
Words
Values: strings with alphanumeric characters and . , ; : …
| Operation | Result type |
|---|---|
= | Boolean |
Category
Values: can take only one of "Noun", "Verb", "Pronoun", "Adjective" …
| Operation | Result type |
|---|---|
= | Boolean |
= 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.)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.
| Data element | Type | Why |
|---|---|---|
| Marks out of 100 | Marks | values 0 to 100 |
| Position of a card | SeqNo | 0, 1, …, Max; no arithmetic |
| Number of items | Count | 0, 1, 2, …; + and − allowed |
| Gender | Gender | only M or F |
| City name | City | alphabet characters only |
| Word from a paragraph | Words | alphanumeric and . , ; : |
| Grammatical class | Category | one of Noun, Verb, Pronoun, … |
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.
| Expression | Allowed? | Result type |
|---|---|---|
Marks + Marks | Yes | Marks |
Marks × Marks | No | — |
Marks < Marks | Yes | Boolean |
SeqNo + SeqNo | No | — |
Count − Count | Yes | Count |
Gender = Gender | Yes | Boolean |
Names + Names | No | — |
4.4Choosing the right subtype
To pick a subtype, ask three questions in this order:
- 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.
- Does arithmetic make sense? Adding marks: yes. Adding sequence numbers: no.
- If no arithmetic, is comparing for equality enough? Then the type has only
=.
Look-alikes, and how to tell them apart
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.
Both allow + and −. The difference is the range: Marks stops at 100, Count has no fixed upper limit.
These are fixed lists. Gender allows only M or F. Category allows only words like Noun, Verb, Pronoun, Adjective.
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
| Subtype | Of | Allowed operations | Result type |
|---|---|---|---|
SeqNo | Integer | none | — |
Marks | Integer | + −, < > = | Marks, Boolean |
Count | Integer | + −, < > = | Count, Boolean |
Gender | Character | = | Boolean |
Names, City, Words, Category | String | = | Boolean |
Never allowed: × ÷ on Marks or Count, any arithmetic on SeqNo, and + on strings.
4.5Exam tips and common mistakes
- 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.
- Doing arithmetic on
SeqNo. - Saying
Marks × Marksis allowed or gives Marks. - Forgetting that a comparison gives a Boolean even for subtypes:
Marks < Marksis 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)
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?
A position is a label, not a quantity.
SeqNo: values 0 to Max, and none of the Integer operations make sense.MarksandCountallow + and −.Genderis a Character subtype with only M or F.- Answer: option 3.
Multiple Select Question (MSQ): select all that apply.
Which expressions are allowed?
Marks + MarksMarks × MarksCount − CountNames + NamesGender = GenderMarks 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.
Multiple Choice Question (MCQ): choose the one correct option.
Which value is not valid for its subtype?
MarksCity'F' as GenderCityCheck 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.
< > = give Boolean
No integer operations apply
+ − give the same type
< > = give Boolean
Gender: M or F
char in string?, = give Boolean
Words: alphanumeric and . , ; :
Category: one of Noun, Verb, …
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.
Dates
Values: 0, 1, 2, 3, …, 365
| Operation | Result type |
|---|---|
print | String |
<, >, = | Boolean |
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.
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.
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.
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.
Marks
Values: 0, 1, 2, 3, …, 10000
Stored as: 62.5 is stored as 6250; print(6250) = "62.5"
| Operation | Result type |
|---|---|
print | String |
+, − | Marks |
<, >, = | Boolean |
Amount
Values: 0, 1, 2, 3, …
Stored as: 27.50 is stored as 2750; print(2750) = "Rs. 27.50"
| Operation | Result type |
|---|---|
print | String |
+, − | Amount |
<, >, = | Boolean |
Quantity
Values: 0, 1, 2, 3, …
Stored as: 1.25 is stored as 125; print(125) = "1.25"
| Operation | Result type |
|---|---|
print | String |
+, − | Quantity |
<, >, = | Boolean |
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).Add 62.5 and 17.25 marks.
- 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 ✓.
A bill has two items costing Rs. 27.50 and Rs. 12.75. Find the total using the Amount type.
- Stored:
27.50 → 2750and12.75 → 1275. - Add the integers:
2750 + 1275 = 4025, an Amount. print(4025) = "Rs. 40.25".
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.)
- 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.
stored = value × 100, and printed = stored ÷ 100 shown with 2 decimals (Amount adds Rs.).
| Real value | Stored | Printed |
|---|---|---|
| 62.5 marks | 6250 | "62.5" |
| 100 marks (maximum) | 10000 | "100" |
| Rs. 27.50 | 2750 | "Rs. 27.50" |
| Rs. 0.05 | 5 | "Rs. 0.05" |
| 1.25 kg | 125 | "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:
| Date | Leap year | Non-leap year |
|---|---|---|
| 1 Jan | 0 | 0 |
| 1 Feb | 31 | 31 |
| 1 Mar | 60 | 59 |
| 1 Apr | 91 | 90 |
| 1 May | 121 | 120 |
| 1 Jun | 152 | 151 |
| 1 Jul | 182 | 181 |
| 1 Aug | 213 | 212 |
| 1 Sep | 244 | 243 |
| 1 Oct | 274 | 273 |
| 1 Nov | 305 | 304 |
| 1 Dec | 335 | 334 |
Example: 25 Dec is 335 + 24 = 359 in a leap year and 334 + 24 = 358 otherwise.
5.5Exam tips and common mistakes
- 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.
- Multiplying by 10 instead of 100 (
62.5 → 625is wrong, it is6250). - Losing the trailing zero:
27.50 → 275is wrong, it is2750. - 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)
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?
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
Numerical Answer Type (NAT).
In a leap year 1 Dec is stored as 335 and 1 Jan as 0. What number stores 25 Dec?
Stored value = number for the 1st of the month + (day − 1).
- 25 Dec is 24 days after 1 Dec.
- 335 + 24 = 359.
- Answer: 359
Multiple Choice Question (MCQ): choose the one correct option.
An Amount is stored as 2505. What does print show?
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.
Multiple Select Question (MSQ): select all that apply.
Choose the correct reasons and facts about scaling by 100.
print scales the number back down.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.
0 = 1 Jan, 31 = 1 Feb
print gives a String
Range: 0 to 10000
print(6250) = "62.5"
print(2750) = "Rs. 27.50"
print(125) = "1.25"
At most 2 decimals: exact integer
Operations: print, + −, < > =
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)
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 field | Type of field | Example value |
|---|---|---|
sequence no: | SeqNo | 9 |
name: | Names | Clarence |
gender: | Gender | M |
date of birth: | Dates | 6 Dec |
city: | City | Bengaluru |
mathsMarks: | Marks | 63 |
physicsMarks: | Marks | 88 |
chemistryMarks: | Marks | 73 |
totalMarks: | TMarks | 224 |
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 field | Type of field |
|---|---|
sequence no: | SeqNo |
word: | Words |
category: | Category |
letterCount: | Count |
6.2List
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 aMarksCardrecord.ParagraphWordList: the data type for our word data set. Each element is aWordInPararecord.ShoppingBillList: the data type for the shopping bill data set. For this we first define the Record data type for a shopping bill.
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.
Record
| Name of field | Type |
|---|---|
sequence no: | SeqNo |
storeName: | Name |
customerName: | Name |
items: | ItemList |
totalBillValue: | Amount |
Record
| Name of field | Type |
|---|---|
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.)
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.
In the marks card, why is totalMarks of type TMarks and not Marks?
- 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 ofMarks. - So the total needs its own type: the same as
Marksbut with range0 … 300.
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.
| Item | Model | Why |
|---|---|---|
| All marks cards | List (MarksCardList) | a sequence of MarksCard records |
| One marks card | Record (MarksCard) | named fields of different types |
| Items on one bill | List (ItemList) | a sequence of Item records |
| One item | Record (Item) | name, category, quantity, price, cost |
| Words of a paragraph | List (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.
| Level | Describes | Example |
|---|---|---|
| Basic type | one simple value | Integer, Boolean |
| Subtype | one value, with restrictions | Marks, Gender |
| Record | one card: several named fields, types can differ | MarksCard |
| List | many items, usually all of the same type | MarksCardList |
Think one thing, many attributes. Fields have names and can have different types. Size is fixed by the definition.
Think many things, one kind. Elements usually share one type. Size can grow with the data.
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
- List every piece of information the card holds.
- Give each one the most specific type (Names rather than String, Count rather than Integer).
- Write the field names and types in a table (add an example value if asked).
- 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
- 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.
- Typing
totalMarksasMarks. 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)
Multiple Choice Question (MCQ): choose the one correct option.
Each of three subjects is marked out of 100. Which type should hold the total?
The total can go past the range of Marks.
- A total can reach 300, which is outside Marks (0 to 100).
TMarksis Marks with range 0 to 300.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
In the ShoppingBill record, which field holds a List?
A field that holds many entries of one kind is a List of a record.
itemshas typeItemList, a List ofItemrecords.- The other three are single values: Name, Amount and Name.
- Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
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:
MarksCardListis a List ofMarksCardrecords. - Answer: options 1, 2 and 3.
Numerical Answer Type (NAT).
How many fields does the MarksCard record have?
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
Week 1 Summary Sheet
Everything from Week 1 on one sheet. Use it for a last-minute revision.
Flowcharts
- Terminal: Start or End
- Process: changes the value of variables
- Flowline: order of execution
- Decision: picks the path, Yes (True) or No (False)
- 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
- 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
- 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
| Type | Values | Operations and result type |
|---|---|---|
| Boolean | True, False | AND, OR give Boolean |
| Integer | … −2, −1, 0, 1, 2 … | + − × ÷ give Integer (22 ÷ 7 = 3); < > = give Boolean |
| Character | A-Z, a-z, 0-9, special characters | = gives Boolean |
| String | Any sequence of characters | char in string?, = give Boolean |
Subtypes
| Subtype | Of | Values | Operations |
|---|---|---|---|
| SeqNo | Integer | 0 … Max | none make sense |
| Marks | Integer | 0 … 100 (or 0 … 10000 when scaled) | + − give Marks; < > = give Boolean |
| Count | Integer | 0, 1, 2, … | + − give Count; < > = give Boolean |
| Dates | Integer | 0 … 365 | print gives String; < > = give Boolean |
| Amount, Quantity | Integer | 0, 1, 2, … | print gives String; + − keep the type; < > = give Boolean |
| Gender | Character | M or F | = gives Boolean |
| Names, City | String | only alphabet characters | = gives Boolean |
| Words | String | alphanumeric and . , ; : … | = gives Boolean |
| Category | String | one of Noun, Verb, Pronoun, Adjective, … | = gives Boolean |
Transforming values and complex types
- 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
- 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
- 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
- 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
| Fact | Value |
|---|---|
| Maximum of whole-number Marks | 100 |
| Maximum of TMarks (3 subjects) | 300 |
| Maximum of scaled Marks | 10000 |
| Scale factor for 2 decimals | × 100 |
| Dates range (leap year) | 0 … 365 |
| 1 Dec in a leap year | 335 |
| Integer division | 22 ÷ 7 = 3 |