Clastify logo
Subjects
Features
Review
HOT
Tutoring

B2.1: Programming fundamentals

Master IB Computer Science B2.1: Programming fundamentals with notes created by examiners and strictly aligned with the syllabus.

This content can't be printed from the browser. Use Export PDF with Pro for an offline copy.

IB Syllabus Requirements for Programming fundamentals

B2.1.1

Variables, data types and scope

B2.1.2

Extracting and manipulating substrings

B2.1.3

Handling exceptions

B2.1.4

Finding and correcting bugs

B2.1.1

VARIABLES, DATA TYPES AND SCOPE

Constructing a program means choosing suitable variables and operations; tracing it means following execution and recording how its values change. A correct trace follows the instructions actually written, not what the programmer intended.

Choosing a data type

A variable associates a name with a value that a program can use or change. Its data type determines the kind of value it represents and which operations are appropriate.

Data typeWhat it representsJavaPython
Boolean valueEither true or falseboolean, for example truebool, for example True
charOne characterchar, for example 'R'No separate character type: use a one-character str
decimalA number with a fractional partCommonly double, for example 1.5Commonly float, for example 1.5
integerA whole numberint, for example 2int, for example 2
stringA sequence of charactersString, for example "Repair"str, for example "Repair"

Java declarations specify types explicitly. Python associates a type with the assigned value, so assigning an integer does not require writing a type declaration. A digit stored in a string is text, not automatically a number on which arithmetic can be performed.

Global and local scope

Scope is the region of a program in which a name can be accessed. A global variable is available across functions in its enclosing program or module; a local variable belongs to a particular function, method or block.

In Python, a variable defined at module level is global. A function can read it without a special declaration; assigning to that global name from inside the function requires the global declaration. Prefer local variables when a value does not need to be shared, because this limits unintended changes elsewhere.

Java has no free-standing global variables. A class-level static field provides shared state for the methods in that class. Variables declared inside a method are local to that method, and variables declared inside a block are restricted to that block.

The scope diagram separates the shared fee from the local values count, category, label, active and total. The calculation reads the shared value but does not change it.

Paired worked programs

A repair desk calculates a total from two units charged at 1.5 each. The program uses all five required data types and prints Repair R 3.0.

Java

1  public class RepairCharge {
2      static double fee = 1.5;
3      static void showCharge() {
4          int count = 2;
5          char category = 'R';
6          String label = "Repair";
7          boolean active = true;
8          double total = count * fee;
9          if (active) {
10             System.out.println(label + " " + category + " " + total);
11         }
12     }
13     public static void main(String[] args) {
14         showCharge();
15     }
16 }

Python

1  fee = 1.5
2  def show_charge():
3      count = 2
4      category = 'R'
5      label = "Repair"
6      active = True
7      total = count * fee
8      if active:
9          print(label + " " + category + " " + str(total))
10 show_charge()

Python needs an explicit string conversion for total when concatenating it with strings. Java performs that conversion as part of string concatenation.

Trace of one run

A dash means that the variable has not yet received a value. The local variables cease to be accessible when the method or function returns.

EventfeecountcategorylabelactivetotalOutput
Shared value assigned1.5——————
Assign count1.52—————
Assign category1.52R————
Assign label1.52RRepair———
Assign active1.52RRepairtrue——
Calculate total1.52RRepairtrue3.0—
Condition is true; print1.52RRepairtrue3.0Repair R 3.0

Terms to use: global variables, local variables, data types, Boolean value, char, decimal, integer, string, construct, trace.

B2.1.2

EXTRACTING AND MANIPULATING SUBSTRINGS

To construct a substring-processing program, first identify the character positions to extract, then apply the required changes and assemble the result. Check the boundaries separately from the manipulation: an incorrect starting position can produce plausible but wrong text.

Extracting the correct characters

A substring is a contiguous sequence of characters within a string. String positions are indexed from zero in both Java and Python.

For BX-417-ready, the identifier 417 occupies indices 3, 4 and 5. The status ready starts at index 7 and continues to the end of the string.

OperationJavaPython
Extract from start index up to, but excluding, end indexsubstring() with start and end argumentsA slice with start and end positions
Extract from a start index to the endsubstring() with one argumentA slice with the end omitted
Join stringsString concatenation using +String concatenation using +
Replace matching textreplace()replace()
Convert letters to uppercasetoUpperCase()upper()

For the identifier, use start index 3 and end index 6: the start is included, but the end is excluded. The extracted length is therefore 6 − 3 = 3 characters.

Alter, concatenate and replace

The figure follows three operations on BX-417-ready: extracting 417, altering ready to READY, and concatenating these pieces into Parcel 417: READY. A separate replacement produces BX-417-held.

Strings are immutable in both languages: these operations produce new strings rather than modifying individual characters in the existing string. Assign the returned value to a variable if it is needed later.

Paired worked programs

Java

1  public class ParcelLabel {
2      public static void main(String[] args) {
3          String text = "BX-417-ready";
4          String identifier = text.substring(3, 6);
5          String status = text.substring(7);
6          status = status.toUpperCase();
7          String result = "Parcel " + identifier + ": " + status;
8          String updated = text.replace("ready", "held");
9          System.out.println(result);
10         System.out.println(updated);
11     }
12 }

Python

1  text = "BX-417-ready"
2  identifier = text[3:6]
3  status = text[7:]
4  status = status.upper()
5  result = "Parcel " + identifier + ": " + status
6  updated = text.replace("ready", "held")
7  print(result)
8  print(updated)

Trace of one run

The original text remains BX-417-ready throughout. In particular, replacing text to create updated does not change text or the previously constructed result.

EventtextidentifierstatusresultupdatedOutput
Assign originalBX-417-ready—————
Extract identifierBX-417-ready417————
Extract statusBX-417-ready417ready———
Alter statusBX-417-ready417READY———
Concatenate resultBX-417-ready417READYParcel 417: READY——
Replace textBX-417-ready417READYParcel 417: READYBX-417-held—
Print resultBX-417-ready417READYParcel 417: READYBX-417-heldParcel 417: READY
Print updatedBX-417-ready417READYParcel 417: READYBX-417-heldBX-417-held

Terms to use: strings, substrings, extract, manipulate, altering, concatenating, replacing.

B2.1.3

HANDLING EXCEPTIONS

Programs use exception handling to respond deliberately when an operation fails during execution. Describe both the possible failure and how control moves to a handler rather than continuing normally through the failed operation.

Where programs can fail

An exception signals a failure during execution that interrupts the normal sequence of instructions. Exception handling provides a controlled route for responding to such a failure.

Potential point of failureExampleAppropriate response
Unexpected inputsText such as many is supplied where a whole number is neededValidate the input and handle a failed conversion
Resource unavailabilityA required file cannot be opened or a service cannot be reachedHandle the access failure, report the problem or use an appropriate alternative
Logic errorsA calculation subtracts a charge when it should add itLocate and correct the faulty reasoning; use tests to check the result

A logic error does not necessarily raise an exception. A program can finish normally and still produce the wrong answer. Exception handling therefore supports reliability, but it does not replace input validation, testing or debugging.

How the constructs work

The try block contains operations that may fail. Java uses catch to handle a matching exception; Python uses except. If an exception occurs, the remaining instructions in that try block are skipped and execution moves to a matching handler.

The finally block runs after the attempt, whether the operation succeeds or a handled exception occurs. It is used for actions that should happen on either route, such as cleanup. After a handled failure and its finally block, execution can continue after the whole construct.

The control-flow figure shows the two routes: try leads directly to finally on success, or through catch / except on a matching failure. Both routes then reach continuation.

Handle exception types that the program can respond to meaningfully. A handler that silently ignores every failure can conceal defects and leave the program in an unsuitable state.

Paired worked programs

These programs attempt to convert many to an integer. The conversion fails, so the normal output inside try is skipped. The handler prints Enter a whole number, and finally prints Attempt finished.

Java

1  public class SeatInput {
2      public static void main(String[] args) {
3          String supplied = "many";
4          try {
5              int seats = Integer.parseInt(supplied);
6              System.out.println(seats);
7          } catch (NumberFormatException error) {
8              System.out.println("Enter a whole number");
9          } finally {
10             System.out.println("Attempt finished");
11         }
12     }
13 }

Python

1  supplied = "many"
2  try:
3      seats = int(supplied)
4      print(seats)
5  except ValueError:
6      print("Enter a whole number")
7  finally:
8      print("Attempt finished")

Trace of the failure route

The failed conversion never assigns a value to seats. Java signals NumberFormatException; Python signals ValueError.

EventsuppliedseatsOutput
Assign input textmanyNot assigned—
Attempt conversion; exception raisedmanyNot assigned—
Matching handler runsmanyNot assignedEnter a whole number
Finally block runsmanyNot assignedAttempt finished

If the input text were 4, the conversion would succeed, the handler would be skipped, and the output would be 4 followed by Attempt finished.

Terms to use: unexpected inputs, resource unavailability, logic errors, exception handling, try/catch, try/except, finally block.

B2.1.4

FINDING AND CORRECTING BUGS

Use debugging techniques to find the first point where a program's behaviour differs from its intended behaviour, then correct the cause and run it again. A useful debugging record connects an observed value to the instruction that produced it.

Making execution visible

Debugging is the process of locating and correcting faults in a program. The following techniques expose different aspects of execution; other techniques also exist.

TechniqueHow to use itWhat it reveals
Trace tablesExecute instructions manually and record changes to variables and outputThe exact sequence of calculated values
Print statementsTemporarily display selected values at important pointsWhat the running program actually contains at those points
Breakpoint debuggingPause execution at a chosen line and inspect the program stateValues immediately before a suspicious instruction executes
Step-by-step code executionExecute one instruction at a time while watching valuesThe instruction where behaviour first diverges from the intention

A trace table can be prepared without running the program. Print statements reveal values during a real run, but too many can make the output difficult to follow. Breakpoints and stepping allow inspection without inserting temporary output instructions.

Worked debugging process

A delivery counter should combine a base quantity of 8 with an extra quantity of 3. The expected total is 11, but a faulty version subtracts the extra quantity and produces 5. Tracing the calculation identifies subtraction as the cause; the correction is to use addition.

The debugging figure follows this sequence: expected total 11, observed total 5, inspect subtraction, replace with addition, rerun, observed total 11. Rerunning matters because editing the suspected line is not itself evidence that the fault has been removed.

The paired programs below contain the corrected calculation and a temporary print statement before it. That first output checks the inputs; the second checks the result.

Java

1  public class DeliveryTotal {
2      public static void main(String[] args) {
3          int base = 8;
4          int extra = 3;
5          System.out.println(base + " " + extra);
6          int total = base + extra;
7          System.out.println(total);
8      }
9  }

Python

1  base = 8
2  extra = 3
3  print(base, extra)
4  total = base + extra
5  print(total)
6  # Remove the temporary input print after checking.

Trace of the corrected run

EventbaseextratotalOutput
Assign base8———
Assign extra83——
Print inputs83—8 3
Calculate total8311—
Print result831111

For breakpoint debugging, pause before Java line 6 or Python line 4. Inspect base and extra, then step over the calculation and inspect total. In the faulty version, this would expose the change to 5 at the calculation itself, rather than merely showing an incorrect final output.

Once the calculation is correct, remove the temporary input print and run the program again. Also check other suitable inputs: one successful run confirms that run, not every possible case.

Terms to use: debugging techniques, trace tables, breakpoint debugging, print statements, step-by-step code execution.

Were those notes helpful?

B2.2 Data structures