Clastify logo
Subjects
Features
Review
HOT
Tutoring

B2.3: Programming constructs

Master IB Computer Science B2.3: Programming constructs 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 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 and dependencies

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.

Consider a booking for three activity sessions. Each session costs 20 credits, and a discount of 10 credits applies once to the whole booking. The sequence diagram follows Set inputs → Calculate subtotal → Subtract discount → Print total.

Worked program: calculate before printing

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.

ActionpricesessionsdiscountsubtotaltotalOutput
Set price20—————
Set sessions203————
Set discount20310———
Calculate subtotal2031060——
Calculate total203106050—
Print total20310605050

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.

Avoiding errors caused by execution order

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.

Choosing a branch

Selection chooses which block of instructions to execute according to whether a condition is true or false.

StructureBehaviour
if aloneExecutes its block when the condition is true; otherwise skips it.
if with elseChooses between two alternative blocks.
if, followed by else if in Java or elif in PythonTests further conditions when earlier conditions are false.
Final elseHandles 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.

Building conditions

Relational operators compare values and produce a Boolean result.

OperatorMeaning
<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.

OperationJavaPythonResult is true when…
AND&&andBoth conditions are true.
OR||orAt least one condition is true.
NOT!notThe 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 =.

Worked program: admission charge

A community workshop applies these rules in order:

  • An age below 0 or above 120 is invalid; the charge is 0.
  • An age of 12 or below, or 65 or above, receives a charge of 4.
  • Otherwise, a member whose membership is not suspended pays 6.
  • Everyone else pays 10.
The decision flowchart tests Invalid age?, then Reduced-age charge?, then Active member?. The corresponding outcomes are Charge 0, Charge 4, Charge 6 and Charge 10.

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)
ActionagemembersuspendedchargeOutput
Set age16————
Set membership16true———
Set suspension status16truefalse——
Invalid-age test: false16truefalse——
Reduced-age test: false16truefalse——
Active-member test: true; assign charge16truefalse6—
Print charge16truefalse66

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.

Counted and conditional loops

A loop repeatedly executes a block of instructions. One execution of its body is an iteration.

Loop typeAppropriate useJava and Python
Counted loopThe 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 loopRepetition 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.

Conditions inside and around loops

The loop condition decides whether another iteration happens. An if inside the loop decides which actions happen during that iteration. These are separate decisions.

The loop-control diagram shows Initialize → Test condition → Execute body → Update → Test condition, with a false branch from Test condition to Continue after loop. If the body contains selection, not every instruction in it has to execute on every iteration.

Worked program: earning and spending credits

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.

ActionRoundcreditsridesOutput
Initialize credits—0——
Enter round 110——
Award credits13——
Enter round 2; award nothing23——
Enter round 333——
Award credits36——
Enter round 446——
Award credits49——
Counted loop finishesOut of scope in Java; 4 in Python9——
Initialize rides—90—
First while test is true; spend credits—50—
Record ride—51—
Second while test is true; spend credits—11—
Record ride—12—
Third while test is false—12—
Print credits—121
Print rides—122

Making repetition stop correctly

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.

Functions and inputs

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.

Worked program: reusable hire charges

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.

The function diagram shows Caller → Hours and rate → Charge function → Return charge → Caller. The same function serves both bookings because the inputs can change between calls.

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.

ActionBASE_RATEhoursratechargefirstsecondtotalOutput
Set shared rate3———————
Enter first call323—————
Calculate first charge3236————
Return and assign first3———6———
Enter second call343—6———
Calculate second charge343126———
Return and assign second3———612——
Calculate total3———61218—
Print total3———6121818

Local and global scope

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.

ScopeConsequence
LocalLimits which code can access a value, reducing unintended interference between tasks.
Global or shared class-level stateMakes 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 and maintainability

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.

BenefitHow modularization provides it
ReuseDifferent callers can use the same function with different inputs.
MaintainabilityA rule can be changed in one place rather than in several copied blocks.
ReadabilityMeaningful function names make the program's overall steps easier to follow.
Testing and debuggingA 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.

Were those notes helpful?

B2.2 Data structures

B2.4 Programming algorithms