Data types, variables and constants
A program has to remember things while it runs: a name, a price, whether a door is locked. It keeps data in variables and constants. Each one has a data type: the kind of value it holds.
Write pseudocode in Paper 2, except in the 15-mark scenario, where Python, Visual Basic or Java is also allowed. Follow the question on which declarations are required.
To choose a type, ask what the value is: a count, a measurement, one key press, some text, or yes or no.
| Data type | Holds | Literal examples | Python |
|---|---|---|---|
| INTEGER | a whole number | 5 · -3 | int |
| REAL | a number that can have a fractional part | 4.7 · 0.3 · -4.0 | float |
| CHAR | a single character | 'x' · '@' | str (length 1) |
| STRING | zero or more characters (letters, digits, symbols) | "Year 10" · "" | str |
| BOOLEAN | a logical value | TRUE · FALSE | True · False |
4.0, 0.3). CHAR uses single quotes; STRING, double.Variables, constants, input and output
The ticket program uses both: Price is set once and never changes, while Name, Tickets and Cost get new values on every run.
Variable
A named store whose value can change while the program runs. DECLARE Tickets : INTEGER
Constant
A named value that does not change. It is given a literal, never an expression: CONSTANT Price ← 2.50
DECLARE Name : STRING DECLARE Tickets : INTEGER DECLARE Cost : REAL CONSTANT Price ← 2.50 OUTPUT "Your name?" INPUT Name OUTPUT "How many tickets?" INPUT Tickets Cost ← Tickets * Price OUTPUT Name, ": ", Cost
Price = 2.50 print("Your name?") Name = input() print("How many tickets?") Tickets = int(input()) Cost = Tickets * Price print(Name, ": ", Cost, sep="")
Identifiers (names)
Use meaningful names in PascalCase, e.g. TotalScore. Letters and digits only, starting with a capital letter; no spaces or underscores; never a keyword.
Input and output
INPUT stores a value in a variable. OUTPUT displays values; separate several with commas.
1 Choose a data type for: a person’s age in whole years; a price of 3.99; whether a door is locked.
2 Is "7" a CHAR, a STRING or an INTEGER?
3 Write two lines that declare a variable PetName and input a value into it.
1 INTEGER · REAL · BOOLEAN · 2 STRING: it has double quotes, so it is text, not a number
DECLARE PetName : STRING INPUT PetName
Operators and comments
Most lines of a program either work something out or ask a question about it. Arithmetic operators calculate, relational operators compare two values, and logical operators join conditions.
Arithmetic operators
Write each operator in pseudocode and Python, and work out its result.
| Operation | Pseudocode | Python | 17 and 5 give |
|---|---|---|---|
| add · subtract · multiply | + - * | + - * | 22 · 12 · 85 |
| divide | 17 / 5 | 17 / 5 | 3.4 |
| raise to the power | 2 ^ 3 | 2 ** 3 | 8 |
| integer quotient | DIV(17, 5) | 17 // 5 | 3 |
| remainder | MOD(17, 5) | 17 % 5 | 2 |
DIV and MOD together split one number into two parts. Run the program with 135: DIV gives the full hours and MOD the minutes left over.
// split minutes into hours and minutes DECLARE Minutes : INTEGER DECLARE Hours : INTEGER DECLARE Mins : INTEGER OUTPUT "Enter the minutes" INPUT Minutes Hours ← DIV(Minutes, 60) Mins ← MOD(Minutes, 60) OUTPUT Hours, " h ", Mins, " min"
# split minutes into hours and minutes print("Enter the minutes") Minutes = int(input()) Hours = Minutes // 60 Mins = Minutes % 60 print(Hours, " h ", Mins, " min", sep="")
Relational operators: the result is always BOOLEAN
Each comparison asks a yes-or-no question about two values. Two of them are written differently in Python: equal and not equal.
| equal | not equal | less | less or equal | greater | greater or equal | |
|---|---|---|---|---|---|---|
| Pseudocode | = | <> | < | <= | > | >= |
| Python | == | != | < | <= | > | >= |
| Comparison | Pseudocode | Python |
|---|---|---|
| equal | = | == |
| not equal | <> | != |
| less than | < | < |
| less than or equal | <= | <= |
| greater than | > | > |
| greater than or equal | >= | >= |
Logical operators
One comparison is often not enough: a mark may need to be at least 40 and at most 60. Join two conditions, and say when the whole condition is TRUE.
| Operator | The result is TRUE when… | Example |
|---|---|---|
| AND | both conditions are true | Age >= 13 AND Age <= 19 |
| OR | at least one condition is true (or both) | Day = "Sat" OR Day = "Sun" |
| NOT | it reverses a condition | NOT Found is TRUE when Found is FALSE |
// starts a comment, so write DIV(17, 5) for integer division. Some mark schemes call AND, OR, NOT “Boolean”: use the question’s words.Assignment, equality and powers
- Assignment copies a value using ←; equality compares values using =.
- Python uses = for assignment and == for equality.
- In Python, powers use **; ^ has a different meaning.
1 Work out DIV(23, 4) and MOD(23, 4).
2 Is 7 > 3 AND 2 = 5 TRUE or FALSE?
3 Write a condition that is TRUE when Mark is from 40 to 60, including 40 and 60.
- 123 = 5 × 4 + 3, so DIV gives 5 and MOD gives 3
- 2TRUE AND FALSE = FALSE: AND needs both
- 3
Mark >= 40 AND Mark <= 60
Sequence and selection
Every program, however big, is built from just three structures. Selection is the one that lets it make decisions: a condition chooses which statements run.
Sequence
Statements are carried out one after another, in the order they are written.
Selection
A condition decides which statements run: IF or CASE.
Iteration
The same statements are repeated several times: FOR, WHILE or REPEAT.
IF: nested selection
Follow the input 101: the outer test passes, so the inner IF runs; 101 <= 100 fails, so the output is Too high.
DECLARE Score : INTEGER OUTPUT "Enter the score" INPUT Score IF Score >= 0 THEN IF Score <= 100 THEN OUTPUT "Valid" ELSE OUTPUT "Too high" ENDIF ELSE OUTPUT "Too low" ENDIF
print("Enter the score") Score = int(input()) if Score >= 0: if Score <= 100: print("Valid") else: print("Too high") else: print("Too low")
CASE: choose by the value of one variable
Choice is matched against each value in turn. OTHERWISE catches anything that matches none of them.
DECLARE Choice : INTEGER OUTPUT "1 Add 2 View" INPUT Choice CASE OF Choice 1 : OUTPUT "Add" 2 : OUTPUT "View" OTHERWISE OUTPUT "Invalid" ENDCASE
print("1 Add 2 View") Choice = int(input()) if Choice == 1: print("Add") elif Choice == 2: print("View") else: print("Invalid")
THEN and ELSE by two spaces and their statements by four; close each IF with its own ENDIF. Write each comparison in full: Score >= 0 AND Score <= 100, never Score >= 0 AND <= 100.1 In the nested IF above, what is output when the score is 0?
2 In the CASE above, what is output when the choice is 3?
3 Write an IF statement that outputs "Pass" when Mark is 50 or more, and "Fail" otherwise.
1 Valid: 0 >= 0 is TRUE and 0 <= 100 is TRUE · 2 Invalid: 3 matches no case, so OTHERWISE runs
IF Mark >= 50 THEN OUTPUT "Pass" ELSE OUTPUT "Fail" ENDIF
Iteration: three kinds of loop
Nobody wants to write the same line fifty times. A loop writes it once and repeats it. Use FOR when you know how many times; WHILE tests first; REPEAT tests at the end.
Count-controlled: FOR … TO … NEXT
Runs a fixed number of times, known before the loop starts. The end value is included if the step reaches it.
DECLARE Count : INTEGER FOR Count ← 1 TO 9 STEP 2 OUTPUT Count NEXT Count
for Count in range(1, 10, 2): print(Count)
Count goes up by 2 each time. 11 is past the end value 9, so the loop stops before outputting it.
FOR Count ← 1 TO 9 STEP 2 → range(1, 10, 2): Python excludes its stop value, 10. STEP -1 counts down.Pre-condition: WHILE … DO … ENDWHILE
The condition is tested at the start, so the loop may run zero times.
DECLARE Number : INTEGER Number ← 3 WHILE Number > 0 DO OUTPUT Number Number ← Number - 1 ENDWHILE
Number = 3 while Number > 0: print(Number) Number = Number - 1
Trace it: Number starts at 3
| OUTPUT | Number | What decided it | |
|---|---|---|---|
| start | 3 | line 2 sets Number before the loop | |
| line 2 sets Number before the loop | |||
| pass 1 | 3 | 2 | 3 > 0 is true: output 3, then subtract 1 |
| 3 > 0 is true: output 3, then subtract 1 | |||
| pass 2 | 2 | 1 | 2 > 0 is true: output 2, then subtract 1 |
| 2 > 0 is true: output 2, then subtract 1 | |||
| pass 3 | 1 | 0 | 1 > 0 is true: output 1, then subtract 1 |
| 1 > 0 is true: output 1, then subtract 1 | |||
| end | 0 > 0 is false: the test comes first, so the body does not run again | ||
| 0 > 0 is false: the test comes first, so the body does not run again | |||
Post-condition: REPEAT … UNTIL
The condition is tested at the end, so the loop always runs at least once. It stops when the condition is TRUE.
DECLARE Score : INTEGER REPEAT OUTPUT "Enter a score from 0 to 20" INPUT Score IF Score < 0 OR Score > 20 THEN OUTPUT "Out of range - try again" ENDIF UNTIL Score >= 0 AND Score <= 20
while True: print("Enter a score from 0 to 20") Score = int(input()) if Score < 0 or Score > 20: print("Out of range - try again") if Score >= 0 and Score <= 20: break
Trace it: the inputs are 25, then 12
| Score | Message | What decided it | |
|---|---|---|---|
| pass 1 | 25 | Out of range - try again | 25 is out of range, so the message runs; UNTIL is false: go round again |
| 25 is out of range, so the message runs; UNTIL is false: go round again | |||
| pass 2 | 12 | 12 is in range: no message; UNTIL is true, so the loop stops | |
| 12 is in range: no message; UNTIL is true, so the loop stops | |||
while True: with break gives the same test-at-the-end behaviour.1 What does FOR Count ← 10 TO 0 STEP -5 output?
2 In the WHILE loop above, what is output if Number starts at 0?
3 Write a FOR loop that outputs 2, 4, 6 and 8.
1 10, 5, 0: the end value 0 is reached, so it is included · 2 Nothing: 0 > 0 is FALSE at the start, so the loop runs zero times
DECLARE Number : INTEGER FOR Number ← 2 TO 8 STEP 2 OUTPUT Number NEXT Number
Stopping a loop at a sentinel or a full array
Someone typing in a list may not know how long it will be, but the array has a fixed size and may end up holding fewer values. So keep going only while there is space and the input is not the sentinel, a special value that means stop.
Read the WHILE line first. Each row of the table takes one part of that condition and says what it does.
DECLARE Labels : ARRAY[0:2] OF STRING DECLARE Name : STRING DECLARE Count : INTEGER Count ← 0 OUTPUT "Enter a label or END" INPUT Name WHILE Name <> "END" AND Count < 3 DO Labels[Count] ← Name Count ← Count + 1 IF Count < 3 THEN OUTPUT "Enter a label or END" INPUT Name ENDIF ENDWHILE OUTPUT "Stored: ", Count
| Continue condition | Effect |
|---|---|
| Name <> "END" | The sentinel is tested before storage, so it is never included |
| Count < 3 | Labels[Count] can only use valid indices 0, 1 and 2 |
| Both tests joined by AND | Either a sentinel or a full array stops the loop |
| Read again only if Count < 3 | No extra input is requested after the last available position is filled |
Test each way the loop can stop
For each test, say what is stored and which inputs are never read.
Trace the second test: Ari, Bo, END, Cy
| Stored | Count | Name | What decided it | |
|---|---|---|---|---|
| start | 0 | Ari | Count ← 0, then the first input, Ari, is read before the loop | |
| Count ← 0, then the first input, Ari, is read before the loop | ||||
| pass 1 | Labels[0] ← Ari | 1 | Bo | Ari <> "END" and 0 < 3: store it in Labels[0], read the next input |
| Ari <> "END" and 0 < 3: store it in Labels[0], read the next input | ||||
| pass 2 | Labels[1] ← Bo | 2 | END | Bo <> "END" and 1 < 3: store it in Labels[1], read the next input |
| Bo <> "END" and 1 < 3: store it in Labels[1], read the next input | ||||
| end | Name is END: stop | |||
| Name is END: stop | ||||
AND, and what Count means
- Join the two tests with AND. With OR, the loop would go on when only one test holds: it could store END, or write past the end of the array.
- Count is the number of values accepted.
- For an average, divide the total by Count, and only when Count > 0; unused positions are not part of the mean.
1 The inputs are Ari, then END. What is the last line output?
2 Why is END never stored in Labels?
3 What must change so the program stores up to five labels?
- 1
Stored: 1 - 2
Name <> "END"is tested beforeLabels[Count] ← Name, so the loop stops first - 3declare
ARRAY[0:4], and change bothCount < 3tests toCount < 5
String handling
Names, passwords and messages are all strings, and programs often need to pick them apart: the first letter, the length, one word. A string is a row of characters. Pseudocode counts positions from 1; Python counts indexes from 0.
SUBSTRING(Text, 2, 3) starts at position 2 and takes 3 characters: “amb”. Python Text[1:4] starts at index 1 and stops before 4. These pseudocode examples start at 1; follow a stated starting position of 0 when one is given.
DECLARE Text : STRING DECLARE Part : STRING Text ← "Cambridge" Part ← SUBSTRING(Text, 2, 3) OUTPUT Part OUTPUT LENGTH(Text) OUTPUT UCASE(Text) OUTPUT LCASE(SUBSTRING(Text, 1, 1))
Text = "Cambridge" Part = Text[1:4] print(Part) print(len(Text)) print(Text.upper()) print(Text[0:1].lower())
Work through a string character by character
Some tasks need every character checked in turn, such as counting the words in a sentence. This word count assumes the text is not empty, has one space between words and no space at either end. Then the number of words is the number of spaces plus one.
DECLARE Sentence : STRING DECLARE Position : INTEGER DECLARE Spaces : INTEGER OUTPUT "Enter a sentence" INPUT Sentence Spaces ← 0 FOR Position ← 1 TO LENGTH(Sentence) IF SUBSTRING(Sentence, Position, 1) = " " THEN Spaces ← Spaces + 1 ENDIF NEXT Position OUTPUT "Words: ", Spaces + 1
print("Enter a sentence") Sentence = input() Spaces = 0 for Position in range(len(Sentence)): if Sentence[Position] == " ": Spaces = Spaces + 1 print("Words:", Spaces + 1)
Spaces are characters
LENGTH("Year 10") is 7: the space counts.
Copy text exactly
Case matters inside quotes: “Yes” and “yes” are different strings.
1 Text ← "Keyboard". What is LENGTH(Text)?
2 What is SUBSTRING(Text, 4, 5)?
3 Write one statement that outputs the first letter of Text in lower case.
1 8 · 2 “board”: start at position 4, take 5 characters
OUTPUT LCASE(SUBSTRING(Text, 1, 1))
Procedures and parameters
Long programs get hard to follow, and the same job often turns up in several places. A procedure is a named block of code that does one task, written once and used wherever it is needed. You run it with CALL, and can pass values in through its parameters.
Procedure
A named subroutine that carries out a task. It need not return a value. It is run with CALL.
Function
A subroutine that always returns one value. It is used inside an expression, e.g. an assignment or OUTPUT.
Parameter
A variable in the subroutine header that receives a value (the argument) when the subroutine is called. Up to three are used.
Procedure: perform a task
Two parts: the definition says what to do, and nothing happens until the CALL runs it with Score set to 18.
PROCEDURE ShowScore(Score : INTEGER) OUTPUT "Score: ", Score ENDPROCEDURE CALL ShowScore(18)
def ShowScore(Score): print("Score: ", Score, sep="") ShowScore(18)
Procedures with and without parameters
ShowMenu needs nothing passed in. For ShowScore, follow the 18 from the CALL into Score.
PROCEDURE ShowMenu OUTPUT "1 New game" OUTPUT "2 Quit" ENDPROCEDURE CALL ShowMenu
Parameter or argument?
In PROCEDURE ShowScore(Score : INTEGER), Score is the parameter. In CALL ShowScore(18), 18 is the argument: the value passed in.
1 In PROCEDURE Greet(Name : STRING) and CALL Greet("Sam"), which is the parameter and which is the argument?
2 What does CALL ShowScore(7) output?
3 Write a procedure Stars, with no parameters, that outputs a row of five stars. Then write the line that runs it.
1 Name is the parameter; "Sam" is the argument · 2 Score: 7
PROCEDURE Stars OUTPUT "*****" ENDPROCEDURE CALL Stars
Functions and return values
Sometimes you want a subroutine to work something out and hand the answer back, the way LENGTH hands back the number of characters. A function is a subroutine that returns one value. Its call goes inside an expression, such as an assignment or an OUTPUT.
Function: calculate and return a value
Follow the 7 from the main program into N, then the 49 back out into Answer.
FUNCTION Square(N : INTEGER) RETURNS INTEGER RETURN N * N ENDFUNCTION DECLARE Answer : INTEGER Answer ← Square(7) OUTPUT Answer OUTPUT Square(3) + 1
def Square(N): return N * N Answer = Square(7) print(Answer) print(Square(3) + 1)
Procedure or function?
Both are subroutines, so they are easy to mix up. Compare how each is written and called, and choose the right one for a task.
| Procedure | Function | |
|---|---|---|
| Header | PROCEDURE Name(Param : TYPE) | FUNCTION Name(Param : TYPE) RETURNS TYPE |
| Ends with | ENDPROCEDURE | RETURN value, then ENDFUNCTION |
| Called by | CALL Name(arguments) on its own line | its name inside an expression: X ← Name(arguments) |
| Returns | nothing has to come back | exactly one value, of the type in the header |
| Use it to | carry out a task, e.g. show a menu or store data | calculate one value, e.g. a square or whether a number is odd |
Procedure
| Aspect | Form or purpose |
|---|---|
| Header | PROCEDURE Name(Param : TYPE) |
| Ends with | ENDPROCEDURE |
| Called by | CALL Name(arguments) on its own line |
| Returns | nothing has to come back |
| Use it to | carry out a task, e.g. show a menu or store data |
Function
| Aspect | Form or purpose |
|---|---|
| Header | FUNCTION Name(Param : TYPE) RETURNS TYPE |
| Ends with | RETURN value, then ENDFUNCTION |
| Called by | its name inside an expression: X ← Name(arguments) |
| Returns | exactly one value, of the type in the header |
| Use it to | calculate one value, e.g. a square or whether a number is odd |
FUNCTION Combined(First : INTEGER, Second : INTEGER) RETURNS INTEGER RETURN First + Second ENDFUNCTION OUTPUT Combined(12, 18)
- Combined receives 12 as First and 18 as Second, then returns 30 to the OUTPUT.
- The arguments match the parameters in order and in type.
- Library routines such as ROUND and LENGTH also return values.
1 What does OUTPUT Square(4) - 6 output?
2 Why is CALL Square(5) wrong?
3 Write a function Double that returns its integer parameter times 2. Then output Double(9).
1 Square(4) returns 16, and 16 − 6 = 10 · 2 Square is a function: use its returned value in an expression, e.g. Answer ← Square(5). CALL is for procedures
FUNCTION Double(N : INTEGER) RETURNS INTEGER RETURN N * 2 ENDFUNCTION OUTPUT Double(9)
Scope and maintainable programs
If every subroutine could change every variable, one slip inside a subroutine could spoil a total somewhere else. So where a variable is declared decides where it can be used: its scope. A maintainable program is easy for another programmer to read and change.
Global variable
Declared in the main program; can be used anywhere, including inside subroutines.
Local variable
Declared inside a subroutine; it exists only while that subroutine runs and cannot be used outside it.
Find where each variable is declared in the code, then check which box it sits in.
DECLARE Bonus : INTEGER // add the bonus to a mark FUNCTION Final(Mark : INTEGER) RETURNS INTEGER DECLARE Result : INTEGER Result ← Mark + Bonus RETURN Result ENDFUNCTION Bonus ← 5 OUTPUT Final(12) OUTPUT Bonus
# add the bonus to a mark def Final(Mark): Result = Mark + Bonus return Result Bonus = 5 print(Final(12)) print(Bonus)
Bonusis global.Mark(a parameter) andResultare local toFinal.- Outside the function, use the returned value, not the local name
Result. - Python note: a function can read a global variable, but must state
global Bonusto change it.
Make a program maintainable
A program is changed far more often than it is written, and often by someone else. Name each technique, give an example, and say how it helps another programmer.
| Technique | Example | Why it helps |
|---|---|---|
| Meaningful identifiers | TotalScore, not T | the name shows what is stored, for variables, constants, arrays and subroutines |
| Comments | // calculate the average | explain what each section does, so another programmer can follow it |
| Procedures and functions | CALL ShowMenu | avoids repeated code; splits the program into smaller, easier-to-read parts |
| Indentation and white space | statements inside a loop indented | shows where each block starts and ends |
| Constants | CONSTANT VAT ← 0.2 | a named fixed value can be updated in one place without finding every repeated literal |
1 In the program above, which variables are local to Final?
2 If the program sets Bonus ← 8 instead, what does OUTPUT Final(12) give?
3 Give two ways to make a program easier to maintain, with an example of each.
- 1
MarkandResult - 212 + 8 = 20
- 3any two, e.g. meaningful identifiers (
TotalScore, notT); comments (// calculate the average); a constant (CONSTANT VAT ← 0.2)
One-dimensional arrays
Five scores in five variables means five INPUT lines. An array keeps a fixed number of values of one data type under a single name; each is an element, found by its index.
Why use an array?
One name stores many related values, so a loop with an index variable can input, process or output them all. Without an array, you would need a separate variable and a separate line of code for each value.
DECLARE Scores : ARRAY[0:4] OF INTEGER DECLARE Index : INTEGER FOR Index ← 0 TO 4 OUTPUT "Enter score ", Index + 1 INPUT Scores[Index] NEXT Index Scores[2] ← 20 FOR Index ← 0 TO 4 OUTPUT Scores[Index] NEXT Index
Scores = [0] * 5 for Index in range(5): print("Enter score ", Index + 1, sep="") Scores[Index] = int(input()) Scores[2] = 20 for Index in range(5): print(Scores[Index])
Which indexes are valid
Read the two bounds in each declaration: they give the first and last valid index, and so the number of elements.
| Declaration | Number of elements | Valid indexes |
|---|---|---|
ARRAY[0:4] OF INTEGER | 5 | 0 to 4 |
ARRAY[1:5] OF INTEGER | 5 | 1 to 5 |
ARRAY[1:30] OF STRING | 30 | 1 to 30 |
1 How many elements are in ARRAY[1:12] OF REAL, and which indexes are valid?
2 The program above is given 12, 8, 19, 11, 15. What is Scores[3] at the end?
3 Temps is declared as ARRAY[1:7] OF REAL. Write a loop that outputs every element.
1 12 − 1 + 1 = 12 elements, indexes 1 to 12 · 2 11: index 3 is the fourth element
DECLARE Day : INTEGER FOR Day ← 1 TO 7 OUTPUT Temps[Day] NEXT Day
Two-dimensional arrays
Some data is naturally a table: each student has several test scores. A 2D array is a table of elements of one type: the first index is the row, the second the column. Three students each have two test scores; their names are in a separate 1D array.
| Names[Row] | Scores[Row, 0]Test 1 | Scores[Row, 1]Test 2 | Totaloutput | |||
|---|---|---|---|---|---|---|
| Row 0 | Ari | 12 | 18 | 30 | ||
| Row 1 | Bo | 9 | 14 | 23 | ||
| Row 2 | Cy | 15 | 17 | 32 |
Two loops, one inside the other: the outer loop picks a row, and the inner loop visits that row's two columns before the row's total is output.
DECLARE Scores : ARRAY[0:2, 0:1] OF INTEGER DECLARE Row : INTEGER DECLARE Column : INTEGER DECLARE Total : INTEGER FOR Row ← 0 TO 2 Total ← 0 FOR Column ← 0 TO 1 INPUT Scores[Row, Column] Total ← Total + Scores[Row, Column] NEXT Column OUTPUT Names[Row], ": ", Total NEXT Row
Scores = [[0, 0], [0, 0], [0, 0]] for Row in range(3): Total = 0 for Column in range(2): Scores[Row][Column] = int(input()) Total = Total + Scores[Row][Column] print(Names[Row], ": ", Total, sep="")
Trace the nested loops: the inner loop runs twice for each row
| Row | Column | Input | Total | OUTPUT | What decided it | |
|---|---|---|---|---|---|---|
| row 0 | 0 | 0 | outer loop: Row = 0, so Total ← 0 before the inner loop | |||
| outer loop: Row = 0, so Total ← 0 before the inner loop | ||||||
| col 0 | 0 | 12 | 12 | INPUT Scores[0, 0]; Total = 0 + 12 | ||
| INPUT Scores[0, 0]; Total = 0 + 12 | ||||||
| col 1 | 1 | 18 | 30 | Ari: 30 | INPUT Scores[0, 1]; Total = 12 + 18; the inner loop ends, so output | |
| INPUT Scores[0, 1]; Total = 12 + 18; the inner loop ends, so output | ||||||
| row 1 | 1 | 0 | outer loop: Row = 1, so Total ← 0 before the inner loop | |||
| outer loop: Row = 1, so Total ← 0 before the inner loop | ||||||
| col 0 | 0 | 9 | 9 | INPUT Scores[1, 0]; Total = 0 + 9 | ||
| INPUT Scores[1, 0]; Total = 0 + 9 | ||||||
| col 1 | 1 | 14 | 23 | Bo: 23 | INPUT Scores[1, 1]; Total = 9 + 14; the inner loop ends, so output | |
| INPUT Scores[1, 1]; Total = 9 + 14; the inner loop ends, so output | ||||||
| row 2 | 2 | 0 | outer loop: Row = 2, so Total ← 0 before the inner loop | |||
| outer loop: Row = 2, so Total ← 0 before the inner loop | ||||||
| col 0 | 0 | 15 | 15 | INPUT Scores[2, 0]; Total = 0 + 15 | ||
| INPUT Scores[2, 0]; Total = 0 + 15 | ||||||
| col 1 | 1 | 17 | 32 | Cy: 32 | INPUT Scores[2, 1]; Total = 15 + 17; the inner loop ends, so output | |
| INPUT Scores[2, 1]; Total = 15 + 17; the inner loop ends, so output | ||||||
Total one column: fix the column, loop through the rows
| Scores[Row, 0] | Scores[Row, 1] | |
|---|---|---|
| Row 0 | 12 | 18 |
| Row 1 | 9 | 14 |
| Row 2 | 15 | 17 |
Column 1 is fixed; Row goes 0, 1, 2. The highlighted cells are the only ones read: 18 + 14 + 17 = 49.
DECLARE Row : INTEGER DECLARE Total : INTEGER Total ← 0 FOR Row ← 0 TO 2 Total ← Total + Scores[Row, 1] NEXT Row OUTPUT "Test 2 total: ", Total
Total = 0 for Row in range(3): Total = Total + Scores[Row][1] print("Test 2 total:", Total)
1 How many elements does ARRAY[1:4, 1:3] OF INTEGER hold?
2 Using the array above, what is Scores[1, 0]?
3 Write a loop that totals Test 1 (column 0) for all three students and outputs the total.
1 4 rows × 3 columns = 12 · 2 9: row 1 is Bo, column 0 is Test 1
DECLARE Row : INTEGER DECLARE Total : INTEGER Total ← 0 FOR Row ← 0 TO 2 Total ← Total + Scores[Row, 0] NEXT Row OUTPUT "Test 1 total: ", Total
Parallel arrays, indexing and nested loops
A name is text and a mark is a number, so they cannot share one array of one type. Parallel arrays store related data in separate arrays at the same index: Names[2] and Marks[2] belong to the same student.
Parallel arrays: the same index links related data
| Index 0 | Index 1 | Index 2 | Index 3 | |
|---|---|---|---|---|
| Names[Index] | Ari | Bo | Cy | Dee |
| Marks[Index] | 62 | 45 | 50 | 38 |
One Index reads both arrays, so the name output always belongs to the mark that was tested.
DECLARE Index : INTEGER FOR Index ← 0 TO 3 IF Marks[Index] >= 50 THEN OUTPUT Names[Index], " passed" ENDIF NEXT Index
for Index in range(4): if Marks[Index] >= 50: print(Names[Index], "passed")
Common array mistakes
Out of range
FOR Index ← 1 TO 5 on ARRAY[0:4] misses element 0 and tries to use element 5, which does not exist.
Value, not index
Scores[19] does not mean “the element holding 19”. The index is the position.
Fixed index in a loop
Inside a loop, use the loop variable as the index: Scores[Index], not Scores[1].
Working with 2D arrays
Nested loops over a 2D array need three things: its size, how to name one element, and the order the loops visit them.
Declare
ARRAY[0:2, 0:1]: 3 rows × 2 columns = 6 elements.
Access
Pseudocode Scores[Row, Column]; Python Scores[Row][Column].
Nested loops
The inner loop runs through every column for each row; reset a row total before the inner loop.
1 Using the arrays above, what are Names[3] and Marks[3]?
2 Data is ARRAY[1:10] OF INTEGER. Which of Data[0] and Data[10] is out of range?
3 Change the loop above so it outputs the name and “resit” for each student with a mark below 50.
1 Dee and 38: the same index, so the same student · 2 Data[0]: the lower bound is 1
DECLARE Index : INTEGER FOR Index ← 0 TO 3 IF Marks[Index] < 50 THEN OUTPUT Names[Index], " resit" ENDIF NEXT Index
Sorting whole records by one field
Sort a class list by family name and each given name must travel with its family name, or people end up with the wrong names. So compare one field, the key, but move every field of the record together. Column 0 is the family name (the key) and column 1 is the given name. Each swap moves both columns.
| 0: familythe key | 1: given | |
|---|---|---|
| Row 0 | Zed | Asha |
| Row 1 | Khan | Milo |
| Row 2 | Khan | Eva |
| 0: familythe key | 1: given | |
|---|---|---|
| Row 0 | Khan | Milo |
| Row 1 | Khan | Eva |
| Row 2 | Zed | Asha |
Compare the two pictures: each given name stays beside its family name. Lines 10 to 15 are the swap that makes that happen.
1DECLARE Row : INTEGER 2DECLARE TempFamily : STRING 3DECLARE TempGiven : STRING 4DECLARE Swapped : BOOLEAN 5REPEAT 6Swapped ← FALSE 7FOR Row ← 0 TO 1 8IF People[Row, 0] > People[Row + 1, 0] 9THEN 10TempFamily ← People[Row, 0] 11TempGiven ← People[Row, 1] 12People[Row, 0] ← People[Row + 1, 0] 13People[Row, 1] ← People[Row + 1, 1] 14People[Row + 1, 0] ← TempFamily 15People[Row + 1, 1] ← TempGiven 16Swapped ← TRUE 17ENDIF 18NEXT Row 19UNTIL NOT Swapped 20FOR Row ← 0 TO 2 21OUTPUT People[Row, 0], " ", People[Row, 1] 22NEXT Row
Preserve the association
- 10–11Save both cells before you overwrite either.
- 12–13Copy both cells up from the next row.
- 14–15Put both saved cells into that row.
Sorting only the family column would wrongly attach Khan to Asha.
A key may leave a tie
- Both Khan records have the same key. This sort keeps Milo before Eva; it does not sort given names.
- To order ties, also compare the given names when the family names are equal (line 8), then do the same whole-row swap.
Parallel arrays and output
- With parallel arrays, swap the same positions in every array.
- To output a 2D array, the inner column loop finishes before the outer loop moves to the next row.
Trace the sort: one row for each comparison
| Row | Swapped | People row 0 | People row 1 | People row 2 | What decided it | |
|---|---|---|---|---|---|---|
| start | ZedAsha | KhanMilo | KhanEva | the rows before sorting | ||
| the rows before sorting | ||||||
| pass 1 | 0 | TRUE | KhanMilo | ZedAsha | Zed > Khan is true: swap both columns of rows 0 and 1 | |
| Zed > Khan is true: swap both columns of rows 0 and 1 | ||||||
| pass 1 | 1 | TRUE | KhanEva | ZedAsha | Zed > Khan is true: swap both columns of rows 1 and 2 | |
| Zed > Khan is true: swap both columns of rows 1 and 2 | ||||||
| pass 2 | 0 | FALSE | Khan > Khan is false: a tie, so no swap: Milo stays before Eva | |||
| Khan > Khan is false: a tie, so no swap: Milo stays before Eva | ||||||
| pass 2 | 1 | Khan > Zed is false: already in order | ||||
| Khan > Zed is false: already in order | ||||||
| end | a whole pass with no swap: Swapped is FALSE, so UNTIL NOT Swapped stops | |||||
| a whole pass with no swap: Swapped is FALSE, so UNTIL NOT Swapped stops | ||||||
1 People holds the rows (Lee, Ana) and (Diaz, Tom). After one swap on the family-name key, what is in row 0?
2 Why does the code save TempGiven as well as TempFamily?
3 Write the IF condition that also puts tied family names in order of given name.
1 Diaz, Tom: the whole record moves · 2 so the given name moves with its family name; otherwise it is overwritten and the names no longer match
IF People[Row, 0] > People[Row + 1, 0] OR (People[Row, 0] = People[Row + 1, 0] AND People[Row, 1] > People[Row + 1, 1])
File handling
Data in variables and arrays is lost when the program stops. Storing it in a file keeps it permanently (non-volatile), so it can be used the next time the program runs, by another program, backed up or copied to another computer.
Follow the name Ari: saved to the file before the program ends, it is still there to load on the next run.
Write a line: open → write → close
DECLARE Name : STRING OUTPUT "Enter a name" INPUT Name OPENFILE "Names.txt" FOR WRITE WRITEFILE "Names.txt", Name CLOSEFILE "Names.txt"
print("Enter a name") Name = input() File = open("Names.txt", "w") File.write(Name + "\n") File.close()
Read a line: open → read → close
DECLARE Name : STRING OPENFILE "Names.txt" FOR READ READFILE "Names.txt", Name CLOSEFILE "Names.txt" OUTPUT "Hello ", Name
File = open("Names.txt", "r") Name = File.readline().rstrip("\n") File.close() print("Hello ", Name, sep="")
File modes
FOR READ: read data from an existing file. FOR WRITE: create the file; any existing data is lost. Open a file in one mode at a time.
Python notes
write() does not add a new line, so add "\n". readline() keeps the line ending, so rstrip() can remove the newline without removing other spaces.
1 Why save a high score in a file rather than only in a variable?
2 Names.txt already holds data. What happens to it when the file is opened FOR WRITE?
3 Write pseudocode that reads one line from Score.txt into Best and outputs it.
1 A variable is in RAM and is lost when the program ends; the file is kept on secondary storage for the next run · 2 It is lost: WRITE creates the file again
DECLARE Best : STRING OPENFILE "Score.txt" FOR READ READFILE "Score.txt", Best CLOSEFILE "Score.txt" OUTPUT Best
Library routines: MOD, DIV, ROUND, RANDOM
Some jobs come up so often that the language already has a routine for them: remainders, rounding, random numbers. Know what each library routine returns and how many arguments it takes.
MOD
The remainder after integer division. MOD(17, 5) → 2
DIV
The whole-number quotient. DIV(17, 5) → 3
ROUND
Rounds to a number of decimal places: two arguments. ROUND(12.346, 2) → 12.35
RANDOM
A random real number from 0 to 1 inclusive; it takes no arguments.
Patterns that come up again and again
For each job, compare the pseudocode with the Python, then check the value it gives.
| Purpose | Pseudocode | Python | Result |
|---|---|---|---|
| random whole number 1 to 6 | ROUND(RANDOM() * 5, 0) + 1 | random.randint(1, 6) | 1, 2, 3, 4, 5 or 6 |
| random whole number Min to Max | ROUND(RANDOM() * (Max - Min), 0) + Min | random.randint(Min, Max) | Min to Max |
| round to 1 decimal place | ROUND(28 / 5, 1) | round(28 / 5, 1) | 5.6 |
| is N even? | MOD(N, 2) = 0 | N % 2 == 0 | TRUE / FALSE |
| 135 minutes in h and min | DIV(135, 60) · MOD(135, 60) | 135 // 60 · 135 % 60 | 2 · 15 |
random whole number 1 to 6
| Language | Expression |
|---|---|
| Pseudocode | ROUND(RANDOM() * 5, 0) + 1 |
| Python | random.randint(1, 6) |
Result: 1, 2, 3, 4, 5 or 6
random whole number Min to Max
| Language | Expression |
|---|---|
| Pseudocode | ROUND(RANDOM() * (Max - Min), 0) + Min |
| Python | random.randint(Min, Max) |
Result: Min to Max
round to 1 decimal place
| Language | Expression |
|---|---|
| Pseudocode | ROUND(28 / 5, 1) |
| Python | round(28 / 5, 1) |
Result: 5.6
is N even?
| Language | Expression |
|---|---|
| Pseudocode | MOD(N, 2) = 0 |
| Python | N % 2 == 0 |
Result: TRUE / FALSE
135 minutes in h and min
| Language | Expression |
|---|---|
| Pseudocode | DIV(135, 60) · MOD(135, 60) |
| Python | 135 // 60 · 135 % 60 |
Result: 2 · 15
The first pattern at work: the loop keeps rolling until a 6 comes up, counting the rolls.
// roll a dice until a 6 appears DECLARE Roll : INTEGER DECLARE Rolls : INTEGER Rolls ← 0 REPEAT Roll ← ROUND(RANDOM() * 5, 0) + 1 Rolls ← Rolls + 1 UNTIL Roll = 6 OUTPUT "A 6 after ", Rolls, " rolls"
# roll a dice until a 6 appears import random Rolls = 0 while True: Roll = random.randint(1, 6) Rolls = Rolls + 1 if Roll == 6: break print("A 6 after ", Rolls, " rolls", sep="")
How ROUND(RANDOM() * 5, 0) + 1 gives a dice roll
- RANDOM takes no arguments; each step changes the range.
- Round to 0 decimal places: rounding to 1 place could leave a fraction.
1 Work out MOD(29, 6) and DIV(29, 6).
2 What does ROUND(7.456, 1) give?
3 Write a pseudocode expression for a random whole number from 1 to 10.
- 129 = 4 × 6 + 5, so MOD gives 5 and DIV gives 4
- 27.5: one decimal place, and the next digit 5 rounds up
- 3
ROUND(RANDOM() * 9, 0) + 1: RANDOM() * 9 is 0 to 9, rounding gives 0 to 9, adding 1 gives 1 to 10
Python’s round() rounds an exact half to the even number, so round(2.5) is 2. random.randint(1, 6) gives a whole number directly, so Python code does not need the rounding step.
Designing a larger program from requirements
A long program question can look like a wall of text, but it is built from small parts you already know. Before writing loops, sort the instructions into the data you are given, the processing to do and the results to output.
Translate a requirement into a data operation
For each requirement, decide what the code must do and where in the program it goes.
| Requirement | Design decision | Where it belongs |
|---|---|---|
| Data are already in named arrays | Use those names and bounds; keep each record's matching index | Before coding: do not input preloaded data again |
| Each entered value must satisfy a rule | Repeat that value's input until valid; store only a valid value | Inside the loop for that record |
| Report a statistic for each row | Reset its total or count before that row's columns | Inside the outer loop, before the inner loop |
| Report a result for all records | Initialise once, then update for each record | Initialise before the loop; output after it |
| Report the name with the highest or lowest result | Keep the index of the winner as well as its value | Update both together; read the name at that index |
See where each part goes
Find the three comments in the code: each marks where the requirements from the table land.
DECLARE Index : INTEGER DECLARE Passes : INTEGER DECLARE Total : INTEGER DECLARE Top : INTEGER // before the loop: initialise once Passes ← 0 Total ← 0 Top ← 0 // inside the loop: one student at a time FOR Index ← 0 TO 3 Total ← Total + Marks[Index] IF Marks[Index] >= 50 THEN Passes ← Passes + 1 ENDIF IF Marks[Index] > Marks[Top] THEN Top ← Index ENDIF NEXT Index // after the loop: output the results OUTPUT "Passed: ", Passes OUTPUT "Top: ", Names[Top], " ", Marks[Top] OUTPUT "Average: ", ROUND(Total / 4, 1)
| Index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| Names | Ari | Bo | Cy | Dee |
| Marks | 62 | 45 | 50 | 38 |
- The same index reads a name and its mark.
- The highest mark, 62, is at index 0, so the name is Ari: keep Top, the index, not just the mark.
- 195 ÷ 4 = 48.75, which ROUND(…, 1) gives as 48.8.
Trace it: one row for each student
| Index | Marks[Index] | Total | Passes | Top | What decided it | |
|---|---|---|---|---|---|---|
| start | 0 | 0 | 0 | before the loop: each is set once | ||
| before the loop: each is set once | ||||||
| pass 1 | 0 | 62 | 62 | 1 | 62 ≥ 50: Passes + 1; 62 > 62 is false | |
| 62 ≥ 50: Passes + 1; 62 > 62 is false | ||||||
| pass 2 | 1 | 45 | 107 | 45 < 50: no pass; 45 > 62 is false | ||
| 45 < 50: no pass; 45 > 62 is false | ||||||
| pass 3 | 2 | 50 | 157 | 2 | 50 ≥ 50: Passes + 1; 50 > 62 is false | |
| 50 ≥ 50: Passes + 1; 50 > 62 is false | ||||||
| pass 4 | 3 | 38 | 195 | 38 < 50: no pass; 38 > 62 is false | ||
| 38 < 50: no pass; 38 > 62 is false | ||||||
| end | after the loop: output Passed: 2, Top: Ari 62, Average: 48.8 (195 ÷ 4 = 48.75) | |||||
| after the loop: output Passed: 2, Top: Ari 62, Average: 48.8 (195 ÷ 4 = 48.75) | ||||||
Make every requirement testable
- Do what the question says about declarations and initialisation: they are different instructions.
- Prompt for each input, label outputs and give units, and use meaningful identifiers and comments for each section.
- Test boundaries (a mark of exactly 50), a top mark at a different index, and any tie or empty case.
- Trace the whole program to check the parts connect.
- Marks go to meeting each requirement and to working logic. Choose one permitted language and use it all the way through.
1 A requirement says “output the average mark”. Where do Total ← 0 and the OUTPUT go?
2 If Cy’s mark were 70, what would the program above output on its Top line?
3 Give two marks you would test the pass check with, and what each should give.
- 1
Total ← 0before the loop; the OUTPUT after it - 2
Top: Cy 70: 70 > 62, so Top becomes index 2 - 350 should pass (the boundary) and 49 should fail (just below it)
Counting how often each value appears
To find how often each face of a dice comes up, you need six counters, one for each face. The value you read picks which counter to add 1 to. Six dice results are 2, 5, 2, 1, 5, 2. Results uses indexes 0–5; Frequency uses face numbers 1–6: two different index ranges.
Follow each arrow: the value in Results picks which counter in Frequency gets 1 added.
DECLARE Frequency : ARRAY[1:6] OF INTEGER DECLARE Face : INTEGER DECLARE Index : INTEGER FOR Face ← 1 TO 6 Frequency[Face] ← 0 NEXT Face FOR Index ← 0 TO 5 Face ← Results[Index] Frequency[Face] ← Frequency[Face] + 1 NEXT Index FOR Face ← 1 TO 6 OUTPUT Face, ": ", Frequency[Face] NEXT Face
Trace which element changes
| Index | Face | Counter changed | What decided it | |
|---|---|---|---|---|
| start | lines 4 to 6 set Frequency[1] to Frequency[6] to 0 | |||
| lines 4 to 6 set Frequency[1] to Frequency[6] to 0 | ||||
| pass 1 | 0 | 2 | Frequency[2] = 1 | Results[0] is 2, so add 1 to counter 2: 0 + 1 |
| Results[0] is 2, so add 1 to counter 2: 0 + 1 | ||||
| pass 2 | 1 | 5 | Frequency[5] = 1 | Results[1] is 5, so add 1 to counter 5: 0 + 1 |
| Results[1] is 5, so add 1 to counter 5: 0 + 1 | ||||
| pass 3 | 2 | 2 | Frequency[2] = 2 | Results[2] is 2, so add 1 to counter 2: 1 + 1 |
| Results[2] is 2, so add 1 to counter 2: 1 + 1 | ||||
| pass 4 | 3 | 1 | Frequency[1] = 1 | Results[3] is 1, so add 1 to counter 1: 0 + 1 |
| Results[3] is 1, so add 1 to counter 1: 0 + 1 | ||||
| pass 5 | 4 | 5 | Frequency[5] = 2 | Results[4] is 5, so add 1 to counter 5: 1 + 1 |
| Results[4] is 5, so add 1 to counter 5: 1 + 1 | ||||
| pass 6 | 5 | 2 | Frequency[2] = 3 | Results[5] is 2, so add 1 to counter 2: 2 + 1 |
| Results[5] is 2, so add 1 to counter 2: 2 + 1 | ||||
| end | six results, and the counts add up to 6 | |||
| six results, and the counts add up to 6 | ||||
Count by value, not by position
- Each pass changes the counter picked by the value read, not by Index. Adding 1 to Frequency[Index] instead would count positions, not results.
- Set every counter to 0 first, even for faces that never appear. The counts add up to 6, one for each result.
- If results are typed in, check that each is 1–6 before using it as an index.
- To find the most or least common face, compare the finished counts and keep the face number (the index) as its label.
1 The results are 3, 3, 6, 1. What are Frequency[3] and Frequency[6] after counting?
2 Why must every counter be set to 0 before counting?
3 Write a loop that finds the face with the highest count and outputs it.
1 2 and 1 · 2 a counter that is never set may hold any value, and faces that never appear must still show 0
DECLARE Most : INTEGER DECLARE Face : INTEGER Most ← 1 FOR Face ← 2 TO 6 IF Frequency[Face] > Frequency[Most] THEN Most ← Face ENDIF NEXT Face OUTPUT "Most common: ", Most
Finding the longest run of values in a row
A library may want two numbers: how many days had no late returns, and the longest stretch of such days in a row. A count answers the first; a run answers the second. Daily late returns are 0, 0, 3, 0, 2, 0, 0, 0, 1. ZeroCount counts every zero day; CurrentRun counts only the zeros in a row so far.
On a zero day both counters go up; any other day sends only CurrentRun back to 0.
1DECLARE Index : INTEGER 2DECLARE ZeroCount : INTEGER 3DECLARE CurrentRun : INTEGER 4DECLARE LongestRun : INTEGER 5ZeroCount ← 0 6CurrentRun ← 0 7LongestRun ← 0 8FOR Index ← 0 TO 8 9IF LateReturns[Index] = 0 10THEN 11ZeroCount ← ZeroCount + 1 12CurrentRun ← CurrentRun + 1 13IF CurrentRun > LongestRun 14THEN 15LongestRun ← CurrentRun 16ENDIF 17ELSE 18CurrentRun ← 0 19ENDIF 20NEXT Index 21OUTPUT "Zero days: ", ZeroCount 22OUTPUT "Longest zero run: ", LongestRun
Count, reset, retain
There are 6 zero days in total, in runs of 2, 1 and 3.
- 18A non-zero input sends CurrentRun back to 0, but LongestRun keeps the best run so far.
- 13–15Update the maximum inside the loop, so a run that reaches the last element is also counted.
Choose the statistic
- Use the statistic the question asks for: a test on the longest period with no late returns compares LongestRun, not ZeroCount.
- If several records each have their own sequence, reset these values inside the outer loop.
| Line | Statement that runs | Index | Zero | Current | Longest | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 8 | FOR Index ← 0 TO 8 | 7 | Index 7 | ||||
| 9 | IF LateReturns[Index] = 0 | test LateReturns[7] is 0: true, so the THEN lines run | |||||
| test LateReturns[7] is 0: true, so the THEN lines run | |||||||
| 11 | ZeroCount ← ZeroCount + 1 | 6 | Zero | 5 + 1 | |||
| 5 + 1 | |||||||
| 12 | CurrentRun ← CurrentRun + 1 | 3 | Current | 2 + 1 | |||
| 2 + 1 | |||||||
| 13 | IF CurrentRun > LongestRun | test 3 > 2 is true, so the next line runs | |||||
| test 3 > 2 is true, so the next line runs | |||||||
| 15 | LongestRun ← CurrentRun | 3 | Longest | a new longest run | |||
| a new longest run | |||||||
The whole trace: one row for each index
| Index | Input | Zero | Current | Longest | What decided it | |
|---|---|---|---|---|---|---|
| start | 0 | 0 | 0 | lines 5 to 7 set all three to 0 | ||
| lines 5 to 7 set all three to 0 | ||||||
| pass 1 | 0 | 0 | 1 | 1 | 1 | 0 = 0: ZeroCount and CurrentRun + 1; 1 > 0, so LongestRun ← 1 |
| 0 = 0: ZeroCount and CurrentRun + 1; 1 > 0, so LongestRun ← 1 | ||||||
| pass 2 | 1 | 0 | 2 | 2 | 2 | 0 = 0: ZeroCount and CurrentRun + 1; 2 > 1, so LongestRun ← 2 |
| 0 = 0: ZeroCount and CurrentRun + 1; 2 > 1, so LongestRun ← 2 | ||||||
| pass 3 | 2 | 3 | 0 | 3 is not 0: CurrentRun ← 0; LongestRun keeps 2 | ||
| 3 is not 0: CurrentRun ← 0; LongestRun keeps 2 | ||||||
| pass 4 | 3 | 0 | 3 | 1 | 0 = 0: ZeroCount and CurrentRun + 1; 1 > 2 is false: LongestRun stays | |
| 0 = 0: ZeroCount and CurrentRun + 1; 1 > 2 is false: LongestRun stays | ||||||
| pass 5 | 4 | 2 | 0 | 2 is not 0: CurrentRun ← 0; LongestRun keeps 2 | ||
| 2 is not 0: CurrentRun ← 0; LongestRun keeps 2 | ||||||
| pass 6 | 5 | 0 | 4 | 1 | 0 = 0: ZeroCount and CurrentRun + 1; 1 > 2 is false: LongestRun stays | |
| 0 = 0: ZeroCount and CurrentRun + 1; 1 > 2 is false: LongestRun stays | ||||||
| pass 7 | 6 | 0 | 5 | 2 | 0 = 0: ZeroCount and CurrentRun + 1; 2 > 2 is false: LongestRun stays | |
| 0 = 0: ZeroCount and CurrentRun + 1; 2 > 2 is false: LongestRun stays | ||||||
| pass 8 | 7 | 0 | 6 | 3 | 3 | 0 = 0: ZeroCount and CurrentRun + 1; 3 > 2, so LongestRun ← 3 |
| 0 = 0: ZeroCount and CurrentRun + 1; 3 > 2, so LongestRun ← 3 | ||||||
| pass 9 | 8 | 1 | 0 | 1 is not 0: CurrentRun ← 0; LongestRun keeps 3 | ||
| 1 is not 0: CurrentRun ← 0; LongestRun keeps 3 | ||||||
| end | output ZeroCount 6 and LongestRun 3 | |||||
| output ZeroCount 6 and LongestRun 3 | ||||||
| Index | Input | ZeroCount | CurrentRun | LongestRun |
|---|---|---|---|---|
| 0 | 0 | 1 | 1 | 1 |
| 1 | 0 | 2 | 2 | 2 |
| 2 | 3 | 2 | 0 | 2 |
| 3 | 0 | 3 | 1 | 2 |
| 4 | 2 | 3 | 0 | 2 |
| 5 | 0 | 4 | 1 | 2 |
| 6 | 0 | 5 | 2 | 2 |
| 7 | 0 | 6 | 3 | 3 |
| 8 | 1 | 6 | 0 | 3 |
1 The first four inputs are 0, 1, 0, 0 and the rest are 2. What are ZeroCount and LongestRun?
2 Which variable answers “what was the longest stretch with no late returns?”
3 What must change to find the longest run of days with more than 2 late returns?
- 1ZeroCount 3, LongestRun 2 (the run 0, 0 at indexes 2 and 3)
- 2LongestRun
- 3the condition becomes
IF LateReturns[Index] > 2; the counting and reset stay the same (rename the variables and outputs to match)