This content can't be printed from the browser. Use Export PDF with Pro for an offline copy.
IB Syllabus Requirements for Programming constructs
B2.3.1
Putting instructions in the correct order
B2.3.2
Choosing actions with selection
B2.3.3
Repeating actions with loops
B2.3.4
Building functions and modules
B2.3.1
PUTTING INSTRUCTIONS IN THE CORRECT ORDER
Construct a program by identifying its required result, working out which values each instruction needs, and placing instructions in an order that makes those values available.
Sequence is the order in which program instructions execute. Changing that order can change the result, even when the individual instructions are unchanged.
An instruction that uses a calculated value must follow the instruction that calculates it. Likewise, a variable must have an appropriate value before it is used, and output should normally follow the calculations it reports.
The required total is 20 × 3 − 10 = 50 credits. The Java and Python versions implement the same sequence.
Java
1 public class BookingTotal {
2 public static void main(String[] args) {
3 int price = 20;
4 int sessions = 3;
5 int discount = 10;
6 int subtotal = price * sessions;
7 int total = subtotal - discount;
8 System.out.println(total);
9 }
10 }
Python
1 price = 20
2 sessions = 3
3 discount = 10
4 subtotal = price * sessions
5 total = subtotal - discount
6 print(total)
The trace records each assignment and the output. A dash means that the variable has not yet been assigned.
| Action | price | sessions | discount | subtotal | total | Output |
|---|---|---|---|---|---|---|
| Set price | 20 | — | — | — | — | — |
| Set sessions | 20 | 3 | — | — | — | — |
| Set discount | 20 | 3 | 10 | — | — | — |
| Calculate subtotal | 20 | 3 | 10 | 60 | — | — |
| Calculate total | 20 | 3 | 10 | 60 | 50 | — |
| Print total | 20 | 3 | 10 | 60 | 50 | 50 |
Subtracting the discount from the session price before multiplying would produce 30 credits instead. That sequence would apply the discount three times rather than once. Printing before the final calculation would also fail to report the required result.
An infinite loop is a loop that continues indefinitely because execution never reaches a stopping condition. Initialize its control values before the loop, update them when necessary, and check that the updates can make the continuation condition false.
Deadlock occurs when activities cannot proceed because each is waiting for a resource held by another. For example, one activity might hold a scanner while waiting for a printer, while another holds the printer while waiting for the scanner.
A consistent resource-acquisition order can prevent this circular wait: both activities should request the scanner before the printer. Resources should also be released when they are no longer needed.
Incorrect output can result from using an old value, calculating too early, or performing an operation in the wrong place. Trace the instructions against the intended calculation, checking intermediate values as well as the final output.
Key terms: sequence, instruction order, program functionality, infinite loops, deadlock, incorrect output.
B2.3.2
CHOOSING ACTIONS WITH SELECTION
Construct selection structures by writing the conditions that distinguish the required cases, arranging those conditions in a suitable order, and assigning an action to each case.
Selection chooses which block of instructions to execute according to whether a condition is true or false.
| Structure | Behaviour |
|---|---|
if alone | Executes its block when the condition is true; otherwise skips it. |
if with else | Chooses between two alternative blocks. |
if, followed by else if in Java or elif in Python | Tests further conditions when earlier conditions are false. |
Final else | Handles the cases not matched by earlier conditions. |
In one chain, only the first matching branch executes. Separate if statements are different: more than one of their blocks may execute.
Relational operators compare values and produce a Boolean result.
| Operator | Meaning |
|---|---|
< | Less than |
<= | Less than or equal to |
> | Greater than |
>= | Greater than or equal to |
== | Equal to |
!= | Not equal to |
Boolean operators combine or reverse Boolean conditions.
| Operation | Java | Python | Result is true when… |
|---|---|---|---|
| AND | && | and | Both conditions are true. |
| OR | || | or | At least one condition is true. |
| NOT | ! | not | The condition being reversed is false. |
A Boolean variable can be a condition on its own; it does not need comparison with true. Use parentheses when necessary to make the grouping of combined conditions clear. Equality testing uses ==, whereas assignment uses =.
A community workshop applies these rules in order:
Java
1 public class AdmissionCharge {
2 public static void main(String[] args) {
3 int age = 16;
4 boolean member = true;
5 boolean suspended = false;
6 int charge;
7 if (age < 0 || age > 120) {
8 charge = 0;
9 } else if (age <= 12 || age >= 65) {
10 charge = 4;
11 } else if (member && !suspended) {
12 charge = 6;
13 } else {
14 charge = 10;
15 }
16 System.out.println(charge);
17 }
18 }
Python
1 age = 16
2 member = True
3 suspended = False
4 if age < 0 or age > 120:
5 charge = 0
6 elif age <= 12 or age >= 65:
7 charge = 4
8 elif member and not suspended:
9 charge = 6
10 else:
11 charge = 10
12 print(charge)
| Action | age | member | suspended | charge | Output |
|---|---|---|---|---|---|
| Set age | 16 | — | — | — | — |
| Set membership | 16 | true | — | — | — |
| Set suspension status | 16 | true | false | — | — |
| Invalid-age test: false | 16 | true | false | — | — |
| Reduced-age test: false | 16 | true | false | — | — |
| Active-member test: true; assign charge | 16 | true | false | 6 | — |
| Print charge | 16 | true | false | 6 | 6 |
Order matters here. Invalid ages are rejected before any discount rule can accept them. A qualifying age also takes priority over membership because its branch occurs first. Check boundary values carefully: an age of exactly 12 belongs in the reduced-charge branch because the comparison includes equality.
Key terms: selection structures, if, else, else if, elif, Boolean operators, AND, OR, NOT, relational operators, program flow.
B2.3.3
REPEATING ACTIONS WITH LOOPS
Construct a loop by deciding what repeats, how repetition is controlled, which values must be initialized, and what changes during each iteration.
A loop repeatedly executes a block of instructions. One execution of its body is an iteration.
| Loop type | Appropriate use | Java and Python |
|---|---|---|
| Counted loop | The required number of repetitions is known before repetition begins. | A Java for loop can initialize, test and update a counter; Python for can visit a sequence supplied by range(). |
| Conditional loop | Repetition depends on a condition that may change while the program runs. | A while loop in either language repeats while its condition is true. |
A while loop tests its condition before executing its body, so its body may execute zero times. A counted loop can also execute zero times if its specified range contains no values.
The loop condition decides whether another iteration happens. An if inside the loop decides which actions happen during that iteration. These are separate decisions.
An activity kiosk runs four rounds. Each successful round earns 3 credits, but round 2 is unsuccessful. A counted loop processes all four rounds, using a conditional statement to exclude round 2.
Afterwards, a conditional loop exchanges credits for rides. Each ride costs 4 credits, and the kiosk allows at most 3 rides. Both requirements must remain true for another ride to be issued.
Java
1 public class ActivityCredits {
2 public static void main(String[] args) {
3 int credits = 0;
4 for (int round = 1; round <= 4; round++) {
5 if (round != 2) {
6 credits += 3;
7 }
8 }
9 int rides = 0;
10 while (credits >= 4 && rides < 3) {
11 credits -= 4;
12 rides++;
13 }
14 System.out.println(credits);
15 System.out.println(rides);
16 }
17 }
Python
1 credits = 0
2 for round_number in range(1, 5):
3 if round_number != 2:
4 credits += 3
5 rides = 0
6 while credits >= 4 and rides < 3:
7 credits -= 4
8 rides += 1
9 print(credits)
10 print(rides)
Python's range stops before its upper bound, so this range supplies 1, 2, 3 and 4. Java's counter starts at 1 and continues while it is at most 4.
The trace shows loop-body entries and changes to the working values. The round column refers to round in Java and round_number in Python.
| Action | Round | credits | rides | Output |
|---|---|---|---|---|
| Initialize credits | — | 0 | — | — |
| Enter round 1 | 1 | 0 | — | — |
| Award credits | 1 | 3 | — | — |
| Enter round 2; award nothing | 2 | 3 | — | — |
| Enter round 3 | 3 | 3 | — | — |
| Award credits | 3 | 6 | — | — |
| Enter round 4 | 4 | 6 | — | — |
| Award credits | 4 | 9 | — | — |
| Counted loop finishes | Out of scope in Java; 4 in Python | 9 | — | — |
| Initialize rides | — | 9 | 0 | — |
| First while test is true; spend credits | — | 5 | 0 | — |
| Record ride | — | 5 | 1 | — |
| Second while test is true; spend credits | — | 1 | 1 | — |
| Record ride | — | 1 | 2 | — |
| Third while test is false | — | 1 | 2 | — |
| Print credits | — | 1 | 2 | 1 |
| Print rides | — | 1 | 2 | 2 |
Initialize working values before the loop. Ensure that updates move the program towards a false continuation condition: here, credits decrease and rides increase.
Check the endpoints of a counted loop to avoid repeating once too many or too few times. For combined conditions, choose the Boolean operator deliberately: AND in the ride loop requires both sufficient credits and an unused ride allowance. OR would allow repetition when only one requirement remained satisfied.
Key terms: looping structures, counted loops, conditional loops, conditional statements, Boolean operators, relational operators.
B2.3.4
BUILDING FUNCTIONS AND MODULES
Construct reusable functions by giving each one a clear task, specifying the inputs it receives and the result it returns, and combining function calls into a complete solution.
A function is a named, reusable block of code that performs a task and may return a value. In Java, these blocks are methods declared inside a class; Python declares functions with def.
A parameter is a named input in a function definition. An argument is the value supplied for that input when the function is called.
A return value is a result passed back to the caller. Returning a result allows the caller to use it in another calculation; printing a result only displays it.
A workshop hires equipment at a rate of 3 credits per hour. Instead of duplicating the multiplication for each booking, define a charge function with parameters for hours and rate. Call it for bookings lasting 2 hours and 4 hours, then add the returned charges.
Java
1 public class HireCharges {
2 static final int BASE_RATE = 3;
3 static int calculateCharge(int hours, int rate) {
4 int charge = hours * rate;
5 return charge;
6 }
7 public static void main(String[] args) {
8 int first = calculateCharge(2, BASE_RATE);
9 int second = calculateCharge(4, BASE_RATE);
10 int total = first + second;
11 System.out.println(total);
12 }
13 }
Python
1 BASE_RATE = 3
2 def calculate_charge(hours, rate):
3 charge = hours * rate
4 return charge
5 def main():
6 first = calculate_charge(2, BASE_RATE)
7 second = calculate_charge(4, BASE_RATE)
8 total = first + second
9 print(total)
10 main()
Each call has its own parameter values and local charge. A dash in the trace means that the variable is not yet assigned or that no charge-function call is active.
| Action | BASE_RATE | hours | rate | charge | first | second | total | Output |
|---|---|---|---|---|---|---|---|---|
| Set shared rate | 3 | — | — | — | — | — | — | — |
| Enter first call | 3 | 2 | 3 | — | — | — | — | — |
| Calculate first charge | 3 | 2 | 3 | 6 | — | — | — | — |
| Return and assign first | 3 | — | — | — | 6 | — | — | — |
| Enter second call | 3 | 4 | 3 | — | 6 | — | — | — |
| Calculate second charge | 3 | 4 | 3 | 12 | 6 | — | — | — |
| Return and assign second | 3 | — | — | — | 6 | 12 | — | — |
| Calculate total | 3 | — | — | — | 6 | 12 | 18 | — |
| Print total | 3 | — | — | — | 6 | 12 | 18 | 18 |
Scope is the region of a program in which a name can be accessed.
A local variable belongs to a limited part of a program, such as a function or method. The charge function's parameters and its charge variable are local: the caller receives the returned value, not direct access to those variables.
A global variable is declared at the program's top level and can be accessed from functions, subject to the language's rules. In Python, the rate constant in this example has global scope; Java has no equivalent top-level global variable, so its rate constant is a class field instead.
| Scope | Consequence |
|---|---|
| Local | Limits which code can access a value, reducing unintended interference between tasks. |
| Global or shared class-level state | Makes a value available more widely, but changes can affect several parts of the program. |
In Python, reading a global name does not require a global declaration. Assigning to that name inside a function normally creates a local variable unless it is declared global. Prefer parameters and return values when data needs to move between functions; this makes the dependencies visible.
Java also gives variables declared inside a block scope within that block. Python if and for blocks do not create a separate local scope; functions do.
Modularization divides a program into smaller, purposeful components with clear responsibilities. Functions are one way to create these components.
A useful function performs one coherent task. Separate calculation from display, and pass the required data into the calculation rather than making it depend on changing shared values.
| Benefit | How modularization provides it |
|---|---|
| Reuse | Different callers can use the same function with different inputs. |
| Maintainability | A rule can be changed in one place rather than in several copied blocks. |
| Readability | Meaningful function names make the program's overall steps easier to follow. |
| Testing and debugging | A small task can be checked independently, helping locate faults. |
For equipment hire, separate functions could calculate charges and format booking details. For a stock-control program, separate functions could check a requested quantity and calculate the remaining stock. In each case, clear inputs and returned results let the components work together without exposing all their internal variables.
Key terms: functions, modularization, reusable blocks of code, inputs, scope, local, global, reusable, maintainable.