Independent reviewer · not a CSC or DICT publicationSign in to practice

Study notes · Program simulation · DICT

Program Simulation

Program simulation means running code in your head. Keep a trace table — one column per variable, one row per step — and never skip a step because it 'looks obvious'.

2023 FAQ (copy)Scope: Tracing code by hand and predicting output.

§1 How to trace

§2 Language details that change answers

DetailBehaviour
Integer division17 / 5 is 3 when both operands are integers; 17 % 5 is 2
Post- vs pre-incrementx++ yields the old value; ++x yields the new value
Short-circuit && and ||The right side is skipped when the left side decides the result
switch without breakExecution falls through into the next case
Array indicesStart at 0; an array of length n ends at n − 1

§3 Worked examples

Example 1

Trace: s = 0; for i = 1 to 4: if i % 2 == 0 then s = s + i else s = s − 1. Output s.

  1. i=1 (odd): s = −1.
  2. i=2 (even): s = 1.
  3. i=3 (odd): s = 0.
  4. i=4 (even): s = 4.

Answer 4

! Common traps

  • Stopping a loop one iteration early or late — check the condition with the boundary value.
  • Assuming C behaves like Java for expressions such as x++ + ++x (undefined in C).