IB COMPUTER SCIENCE | B2 ASSESSMENT
PROGRAMMING: END OF TOPIC REVIEW
Assess programming fundamentals, data structures, constructs, algorithms and file processing through scored retrieval, applied traces and developed written responses.
BEFORE YOU BEGIN
This substantial review covers all 18 B2 objectives. Use several sessions if needed: quick checks, applied traces, then written construction and explanations. Only B2.4.4 and B2.4.5 recursion are HL-only; other objectives are common SL/HL.
Sections A and B award one point for each fully correct automatic item, with no partial credit within an item. Section C has separately suggested content marks. These are original practice questions, not an official IB paper, grade boundary or prediction.
Choose your level below. Write calculations, diagrams and Section C answers in your exercise book before revealing guidance. Answers and selections last while the page remains open.
Automatic total: 48 points. Suggested written total: 108 marks, assessed separately.
C | WRITTEN COMMUNICATION AND SUBJECT KNOWLEDGE
Write in your exercise book before revealing the guidance. The table gives practical guidance based on the IB command terms supplied in the guide; it is not the Cambridge command-word table.
In particular, IB compare focuses on similarities, while distinguish asks for differences. If you need to address both, the question can request each separately. All main commands below are highlighted.
| IB command term | What to provide here | Practical approach |
|---|---|---|
| Construct | Information in diagrammatic or logical form | Supply complete code/algorithm, including initialization, stopping and failure paths. |
| Trace | Follow and record actions of an algorithm | Separate arguments, variables, decisions, outputs and returned results. |
| Calculate | A numerical result with relevant working | Show counts or formula stages before the answer. |
| Describe | A detailed account | Give relevant features and an ordered process where useful. |
| Explain | A detailed account including reasons or causes | Link correct ideas using because, therefore, resulting in or leading to. |
| Compare and contrast | Similarities and differences, referring to both throughout | Use both for shared properties and whereas for differences. |
| Distinguish | Clear differences | State how roles or behaviours differ. |
| Evaluate | An appraisal weighing strengths and limitations | Connect trade-offs to the scenario and support the conclusion. |
A connective earns no automatic mark by itself: it must express an accurate relationship. For example, “resetting total inside the loop discards earlier contributions, therefore the final value includes only the last item” explains a mechanism and consequence. Suggested marks reward subject content, not extra unofficial grammar marks.
C1 | LOCAL STATE AND A SHARED LIST
6 suggested marks | COMMON SL/HL
Use P1. Trace the local parameter, caller variable, returned result and list contents. Then explain why the list and the caller’s number behave differently.
| Stage | Local number | Caller number | Shared list | result |
|---|---|---|---|---|
| Before call | Not active | 10 | [8] | Not assigned |
| After local addition | 12 | 10 | [8] | Not assigned |
| After append | 12 | 10 | [8,12] | Not assigned |
| After return | Call finished | 10 | [8,12] | 12 |
The local parameter is rebound to 12, without rebinding the caller’s number. Both list names refer to the same mutable list, so append changes the object visible to the caller.
SUGGESTED MARKING POINTS
- Local number starts at 10.
- Local addition changes it to 12.
- Caller number remains 10.
- Shared list becomes [8,12].
- Returned result is assigned as 12.
- Explain local rebinding versus shared-object mutation.
Writing focus: Distinguish the names and objects explicitly; use because to explain the different effects.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC2 | CONSTRUCT A STRUCTURED SUBSTRING
6 suggested marks | COMMON SL/HL
A code has the format ABC-2027-0042. Assume its format is already validated. Construct a Python function returning the four-character year and final four-character identifier as two strings. Explain the slice bounds and why the identifier should stay text.
def extract_parts(code):
year = code[4:8]
identifier = code[9:13]
return year, identifier
The year occupies indexes 4 through 7, and the identifier 9 through 12. The stop is excluded. Returning strings preserves the leading zeroes in 0042; converting it to an integer would lose that representation.
SUGGESTED MARKING POINTS
- Function accepts the supplied code as a parameter.
- Correct year slice [4:8].
- Correct identifier slice [9:13] or equivalent last-four slice.
- Returns both results with a defined interface.
- Explain zero-based and excluded-stop bounds.
- Explain preserving leading zeros as text.
Writing focus: Show actual code, then connect the indexing and type choices to the required data.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC3 | CONVERSION AND EXCEPTION FLOW
6 suggested marks | COMMON SL/HL
Construct a Python function accepting raw numeric text and returning 12 divided by its integer value. Return distinct messages for invalid integer text and zero. Explain why one conversion check does not cover both failures.
def divide_from_text(raw):
try:
number = int(raw)
return 12 / number
except ValueError:
return "Use an integer"
except ZeroDivisionError:
return "Zero is not allowed"
Text such as zero fails conversion, whereas "0" converts successfully and fails only at division. Specific handlers distinguish the causes rather than hiding every possible error.
SUGGESTED MARKING POINTS
- Function receives raw text.
- Conversion occurs inside guarded code.
- Valid nonzero conversion returns the numerical result.
- ValueError has the stated distinct response.
- ZeroDivisionError has its own response.
- Explain successful conversion can still leave an invalid divisor.
Writing focus: Make the cause of each path clear rather than describing all failures as bad input.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC4 | DEBUG A LOST RUNNING TOTAL
6 suggested marks | COMMON SL/HL
A loop over [4,7,2] executes total = 0 inside the body immediately before total = total + value. Explain the logic error and a systematic debugging approach, then state the repair and expected total.
Resetting on each iteration discards the accumulated sum, so the totals after the additions are 4,7,2 rather than 4,11,13. Predict 13 independently, then pause before reset/addition and step through while inspecting total and value. Move initialization outside the loop and report the total after processing. Rerun the original case and empty/single-value cases.
SUGGESTED MARKING POINTS
- Identify reset inside body as the cause.
- Show faulty totals 4,7,2 or final 2.
- Predict correct total 13.
- Describe a breakpoint/step/watch or equivalent trace at relevant statements.
- Move initialization outside and keep addition inside.
- Retest the failing case plus an appropriate boundary.
Writing focus: Use cause → changed state → wrong result, then evidence that the repair works.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC5 | SIZE, CAPACITY AND GROWTH
6 suggested marks | COMMON SL/HL
A toy resizable array starts with capacity 2 and size 0, doubling capacity only when an append finds it full. Trace five appends. Evaluate the benefits and costs of this growth strategy compared with a fixed-capacity structure.
| After append | Size | Capacity |
|---|---|---|
| 1 | 1 | 2 |
| 2 | 2 | 2 |
| 3 | 3 | 4 |
| 4 | 4 | 4 |
| 5 | 5 | 8 |
Growth handles an unknown final size, but may allocate unused space and copy existing elements at resize points. Fixed capacity avoids those automatic growth copies but requires a full policy when the limit is reached. This model illustrates a strategy rather than specifying every runtime.
SUGGESTED MARKING POINTS
- Correct sizes 1 through 5.
- Capacities 2,2 after first two appends.
- Third grows to 4, fourth stays 4.
- Fifth grows to 8.
- Explain flexibility versus allocation/copy/unused-space cost.
- Contrast fixed-capacity limit handling with a justified context-dependent conclusion.
Writing focus: State which costs occur occasionally and which depend on the capacity policy.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC6 | CONSTRUCT ROW AND GRAND TOTALS
6 suggested marks | COMMON SL/HL
Construct Python code reporting each row total and one grand total for grid = [[4,7,2],[5,1,6]]. Explain where both accumulators are initialized.
grid = [[4, 7, 2], [5, 1, 6]]
grand_total = 0
for row in grid:
row_total = 0
for value in row:
row_total = row_total + value
grand_total = grand_total + value
print(row_total)
print(grand_total)
Output is 13,12,25. row_total resets once per row, while grand_total must retain all earlier rows, therefore it is initialized before both loops.
SUGGESTED MARKING POINTS
- Outer traversal visits each row.
- Inner traversal visits each value in that row.
- Row accumulator reset in outer body before inner loop.
- Grand accumulator initialized outside both loops.
- Correct updates and output placement.
- Correct outputs with explanation of different retention scopes.
Writing focus: Supply runnable control structure, then explain the placement through the data it must retain.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC7 | STACK FOR UNDO HISTORY
6 suggested marks | COMMON SL/HL
A text editor stores previous text states in a stack before each edit. Trace an initial empty string followed by edits to A and AB, then two undo actions. Explain why a stack suits the requirement and how empty-history handling should work.
Before changing empty text to A, push the empty string. Before changing A to AB, push A. Undo pops A and restores it; the next undo pops the empty string and restores it. That empty string is a valid saved state, not a marker meaning no history. The most recent edit is undone first, matching LIFO. If history has no items, report that undo is unavailable without popping.
SUGGESTED MARKING POINTS
- Save empty string before first edit.
- Save A before second edit.
- First undo restores A.
- Second undo restores empty string.
- Explain LIFO matches most recent edit first.
- Handle truly empty history separately from a saved empty string.
Writing focus: Make the order and the distinction between empty data and empty structure explicit.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC8 | CIRCULAR QUEUE WRAPAROUND
6 suggested marks | COMMON SL/HL
A circular queue of capacity 5 uses front as next read, rear as next write and count as occupancy. Start empty with both indexes 0. Enqueue A,B,C,D; dequeue twice; enqueue E,F,G. Trace the physical slots, logical order and final indexes. Explain how count distinguishes full from empty.
| Final physical index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Stored item | F | G | C | D | E |
Logical order is C,D,E,F,G. front = 2, rear = 2, count = 5. Both indexes can be equal when either empty or full; count = 0 means empty, count = capacity means full. Advance indexes modulo capacity after valid operations.
SUGGESTED MARKING POINTS
- Dequeue removes A then B.
- Final physical slots F,G,C,D,E.
- Logical removal order C,D,E,F,G.
- Final front=2 and rear=2.
- Final count=5.
- Explain count 0 versus capacity distinguishes equal-index states.
Writing focus: Keep physical storage and logical service order in separate labelled views.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC9 | ORDER DEPENDENT CALCULATIONS
6 suggested marks | COMMON SL/HL
A ticket program receives quantity as text. Unit price is 4.50 and a 10% discount applies to the subtotal. Construct the correctly ordered calculation and explain why conversion and intermediate dependencies matter. Assume a valid positive integer quantity.
raw = "3"
quantity = int(raw)
subtotal = quantity * 4.50
discount = subtotal * 0.10
total = subtotal - discount
print(f"{total:.2f}")
The output is 12.15. The subtotal is 13.50, discount 1.35, and the total uses those computed values. Conversion establishes numeric input before arithmetic; reporting before updates can use undefined or stale state.
SUGGESTED MARKING POINTS
- Convert quantity before numeric use.
- Calculate subtotal with the unit price.
- Calculate discount from subtotal at 10%.
- Subtract discount after it exists.
- Format/report after final total is computed.
- Explain dependencies with correct example result 12.15.
Writing focus: Explain which earlier result each later instruction needs.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC10 | CONSTRUCT EXCLUSIVE CATEGORIES
6 suggested marks | COMMON SL/HL
Fictional categories are High for 80–100, Pass for 50–79 and Develop for 0–49. Construct Python selection for an already converted integer mark, rejecting values outside 0–100. Explain why branch order and a chain matter.
def category(mark):
if mark < 0 or mark > 100:
return "Invalid"
elif mark >= 80:
return "High"
elif mark >= 50:
return "Pass"
else:
return "Develop"
Invalid values must not receive valid categories. The high threshold precedes the broad pass threshold because a mark of 85 satisfies both. A chain selects exactly one result; independent printing if statements could produce more than one output.
SUGGESTED MARKING POINTS
- Correct outside-range rejection using OR.
- High condition includes 80–100 after validation.
- Pass condition includes 50–79.
- Remaining valid marks are Develop.
- Explain restrictive threshold before broader overlap.
- Explain exclusive chain versus independent if behaviour.
Writing focus: Use boundaries and an overlapping example to support the explanation.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC11 | LOOP UNTIL A SENTINEL
6 suggested marks | COMMON SL/HL
Construct a program that reads integer values as text until the exact word stop, then reports the total and count of the numeric values. Assume each non-sentinel value is a valid integer. Explain how the sentinel is excluded and the loop progresses.
total = 0
count = 0
raw = input("Integer or stop: ")
while raw != "stop":
value = int(raw)
total = total + value
count = count + 1
raw = input("Integer or stop: ")
print(total, count)
The raw sentinel comparison occurs before conversion or addition. Fresh input at the end permits a changed condition. If stop is the first input, total and count remain 0.
SUGGESTED MARKING POINTS
- Initialize total and count before repetition.
- Obtain initial raw input.
- Test sentinel before conversion.
- Convert/process numeric value and update both accumulators.
- Read fresh input on continuing paths.
- Report after loop and explain first-sentinel zero-data case.
Writing focus: Link input placement to progress rather than just saying the loop repeats.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC12 | MODULAR TEMPERATURE REPORT
6 suggested marks | COMMON SL/HL
Construct functions separating average calculation from message formatting for a nonempty list of numeric temperatures. A coordinating function must return a report string. Explain how this separation supports testing and reuse.
def average(values):
if len(values) == 0:
raise ValueError("No readings")
return sum(values) / len(values)
def format_report(value):
return f"Average: {value:.1f}"
def report(values):
return format_report(average(values))
The caller can print the returned string or display it elsewhere. The calculation can be tested without interactive input or display, while wording can change without changing the arithmetic.
SUGGESTED MARKING POINTS
- Calculation function with explicit input.
- Correct average and empty policy.
- Separate formatting function.
- Coordinator passes returned result correctly.
- Returns report rather than only printing it.
- Explain independent testing or interface reuse through separation.
Writing focus: Show the data moving between interfaces, then state the reason that helps maintenance.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC13 | CALCULATE AND EVALUATE GROWTH
6 suggested marks | COMMON SL/HL
Algorithm X makes two sequential full scans of n items. Algorithm Y performs constant work for every ordered pair of those items. Calculate their standard time bounds, then evaluate scalability if both satisfy the same required output.
X has repeated work n+n=2n, giving O(n). Y has n×n=n², giving O(n²). Doubling n roughly doubles X’s dominant work but multiplies Y’s by four. X has the more favourable asymptotic growth, so is generally preferable for sufficiently large inputs under these models, while constants and implementation can affect small-input timings. Neither statement alone determines auxiliary space.
SUGGESTED MARKING POINTS
- X count 2n from addition.
- X classification O(n).
- Y count n² from nested pairs.
- Y classification O(n²).
- Correct doubling effects.
- Justified scalability judgement with actual-runtime or space limitation.
Writing focus: Show the calculation before the complexity label and connect growth to the scenario.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC14 | CONSTRUCT AND TRACE BINARY SEARCH
6 suggested marks | COMMON SL/HL
Construct an ascending binary search returning an index or -1. Then trace target 20 in [3,7,11,15,19,23,27,31] and explain its sorted-data requirement.
def binary_search(values, target):
low = 0
high = len(values) - 1
while low <= high:
middle = (low + high) // 2
if values[middle] == target:
return middle
elif values[middle] < target:
low = middle + 1
else:
high = middle - 1
return -1
The trace is (low,high,middle,value): (0,7,3,15) → low4; (4,7,5,23) → high4; (4,4,4,19) → low5. Then 5<=4 is false and -1 is returned. Ascending order justifies excluding values on the smaller or larger side after a nonmatch.
SUGGESTED MARKING POINTS
- Initialize inclusive bounds 0 and length−1.
- Use low<=high and a valid whole-number middle.
- Compare stored value and return index on equality.
- Update beyond middle and return -1 only after exhaustion.
- Correct three probes and final empty interval.
- Explain sorted order justifies discarding a side.
Writing focus: Separate construction from trace evidence; distinguish the inspected index from its stored value.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC15 | COMPARE SORTS AND EVALUATE THE COSTS
6 suggested marks | COMMON SL/HL
Compare and contrast optimized bubble sort and standard swap-based selection sort. Evaluate their suitability for a small list where exchanges are expensive and memory is limited. Include time, auxiliary space and stability.
Both use repeated comparisons and can rearrange an existing array with O(1) auxiliary space; both have O(n²) worst-case time. Bubble exchanges adjacent out-of-order pairs and may make many swaps, while selection finds a minimum and performs at most one non-self exchange per pass. Selection has at most n−1 exchanges but always n(n−1)/2 comparisons. Optimized bubble has O(n) sorted-input best case; selection remains O(n²). Strict-greater bubble is stable, standard swap selection is not. For this small write-expensive case, selection may suit if stability is not required; large n or a stability requirement could change the choice.
SUGGESTED MARKING POINTS
- A relevant similarity including constant auxiliary space or quadratic worst case.
- Correct contrasting mechanisms.
- Selection at most n−1 exchanges versus bubble’s potentially quadratic swaps.
- Correct best-case comparison with early-stop condition.
- Correct stability distinction.
- Supported scenario judgement weighing costs and limits.
Writing focus: Refer to both throughout and make the conclusion conditional on the actual requirements.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC16 | CONSTRUCT FILE PROCESSING WITH CLEANUP
6 suggested marks | COMMON SL/HL
scores.txt stores one integer per line. Construct a Python program that skips invalid/blank lines and writes valid count and total to a different file summary.txt. Close resources safely. Explain why input must be read before output replacement and why raw blank lines are not EOF.
total = 0
count = 0
with open("scores.txt", "r", encoding="utf-8") as source:
for line in source:
try:
value = int(line.strip())
except ValueError:
continue
total = total + value
count = count + 1
with open("summary.txt", "w", encoding="utf-8") as report:
report.write(f"Count: {count}\nTotal: {total}\n")
The paths must be distinct. Input processing finishes before opening replacement output; opening the original in w would truncate it. A blank line contains a line terminator and can be followed by more records, while Python raw EOF is "". The iterator handles EOF and the conversion policy skips blanks.
SUGGESTED MARKING POINTS
- Correct input read mode and explicit encoding.
- Sequential traversal through EOF.
- Conversion with explicit skip policy.
- Correct total and count updates outside repeated initialization.
- Different output path, write mode, separators and safe cleanup.
- Explain truncation risk and blank-line/EOF distinction.
Writing focus: Combine working code with the reason for mode and control choices.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC17 | HL | RECURSION MECHANISM AND LIMITS
6 suggested marks | HL ONLY
Explain the call stack and unwinding for factorial(3) using base factorial(0)=1. Then evaluate recursion for this task under a unit-cost arithmetic model.
Calls enter with separate local n values 3,2,1,0. The base returns 1. Waiting calls finish 1×1=1, 2×1=2 and 3×2=6. There are four active factorial frames at maximum depth. The recurrence is clear, but time is O(n) and retained-frame space O(n); a loop can keep O(1) auxiliary variable state in this simplified model. Large valid inputs can exceed stack resources, and arbitrarily large integer arithmetic has additional costs.
SUGGESTED MARKING POINTS
- Separate calls/local n values 3,2,1,0.
- Base result 1.
- Correct returned products through final 6.
- Retained frames explain pending work and maximum four active calls.
- O(n) time and O(n) stack under the stated model.
- Balanced judgement with iterative-space or runtime/arithmetic limit.
Writing focus: Explain how the mechanism creates the resource cost rather than merely listing Big O labels.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentC18 | HL | CONSTRUCT AND TRACE A SINGLE CHAIN
6 suggested marks | HL ONLY
Construct a non-branching recursive function returning the sum of even terms from 2 to n, for a non-negative even integer n. Trace n=6 and explain why the reduction terminates for the stated domain.
def even_sum(n):
if n == 0:
return 0
return n + even_sum(n - 2)
print(even_sum(6))
Arguments descend 6,4,2,0. Results return 0,2,6,12. The non-negative even argument decreases by 2 to 0, so the base case is reachable. There is one recursive call per positive invocation, with selection choosing the base; odd or negative inputs are outside this contract unless a wrapper rejects them.
SUGGESTED MARKING POINTS
- Function and stated non-negative even domain.
- Correct base n==0 returns 0.
- One recursive call with n−2.
- Correct returned addition.
- Trace arguments and returned results distinctly through 12.
- Explain reachable base and non-branching call pattern.
Writing focus: Supply code and both trace directions; do not confuse arguments with accumulated results.
Equivalent accurate wording and methods can be valid. Use the points as self-assessment guidance, not an official IB markscheme.
Revisit related contentCHECK THE QUALITY OF YOUR WRITING
Did you answer the command? For explain, check the reason or cause; for compare, address both items through similarities; for compare and contrast, include differences too; for discuss, balance relevant factors in context; for distinguish, make the differences explicit; for evaluate, weigh strengths and limitations and support your conclusion.
For construct, check labels, connections and completeness. For calculate, show enough working to follow your method and label units. Select two weak responses and rewrite them after revising. Keep the written total separate from your automatic result.
YOUR NEXT REVISION STEP
Submit the automatic sections for targeted revision links.
Record your own written marks using the suggested points. Choose two weaknesses and attempt new examples after revising. Use the B2 revision page for worked content and a personal flashcard list, or return to the IB course index.