IB Computer Science B2.3: Programming constructs

New IB Computer Science syllabus · first exams May 2027 · Theme B · Paper 2 · SL & HL · Python and Java

Every program is built from four constructs: sequence, selection, iteration and functions. B2.3 is about combining them correctly to meet a program's objectives.

StatementTopicCommand term
B2.3.1Correct sequence of instructionsConstruct
B2.3.2Selection structuresConstruct
B2.3.3Looping structuresConstruct
B2.3.4Functions and modularizationConstruct

Key points

B2.3.1 Sequence

The order of instructions changes what a program does. Avoid infinite loops, deadlock and incorrect output by checking that each value is set before it's used.

B2.3.2 Selection

  • Python: if / elif / else
  • Java: if / else if / else

Conditions combine relational operators (<, <=, >, >=, ==, !=) with Boolean operators:

  • Python: and, or, not
  • Java: &&, ||, !

B2.3.3 Loops

  • Counted loops: for, when you know how many repeats you need.
  • Conditional loops: while, when you repeat until a condition changes.

Make sure the loop's condition can actually become false.

B2.3.4 Functions and modularization

  • Functions are reusable blocks of code that take inputs (parameters) and can return a result.
  • Modularization makes code easier to read, reuse, test and maintain.
  • Scope: local vs global variables.

Exam-style question

Construct a while loop that prints numbers starting from 1, stopping as soon as the number exceeds 15 OR the number is divisible by 7, whichever comes first. [5]

Mark scheme

[3] for the correct compound exit condition, [2] for the correct output. It prints 1 to 6, then stops at 7, which is divisible by 7.

Python

n = 1
while n <= 15 and n % 7 != 0:
    print(n)
    n = n + 1

Java

int n = 1;
while (n <= 15 && n % 7 != 0) {
    System.out.println(n);
    n = n + 1;
}

Note: the loop continues while both "keep going" conditions are true. That's why the "stop" condition, "exceeds 15 OR divisible by 7", is written as <= 15 AND not divisible by 7.


Common mistakes that cost marks

  • Inverting a compound condition incorrectly. "Stop when A or B" becomes "continue while not A and not B".
  • Forgetting to update the loop variable, which creates an infinite loop.
  • Using = instead of == in a condition.

Frequently asked questions

What's the difference between elif and else if?
They do the same job. Python writes elif; Java writes else if.

When should I use a for loop rather than a while loop?
Use a counted (for) loop when the number of repeats is known in advance, and a conditional (while) loop when it depends on a condition.


Go further