Programming Fundamentals and Control Structures
Programming Fundamentals and Control Structures
This domain tests the building blocks of programs: variables, data types, operators, input and output, and the three control structures-sequence, selection and iteration. You should be able to trace short code and spot logic errors.
Core rules
- A variable names a storage location; its data type decides valid values and operations. Common types are integer, real or float, character, string and Boolean.
- Assignment stores a value with =; equality comparison uses == in C-like languages. Integer division truncates, so use a real type for fractional results.
- Selection uses if, if...else, if...else if, and switch or case for multi-way choices. Conditions use relational operators such as <, >, <=, >=, == and !=, and logical operators such as AND, OR and NOT.
- Iteration uses for for a known count, while for a pre-test condition, and do...while for at least one execution.
- A counter increments by a fixed amount; an accumulator adds running values. Initialise both before the loop.
- Input should be validated, and output should be clearly labelled.
Worked example
Find the sum of 1 to 10. SET sum = 0 FOR i = 1 TO 10 sum = sum + i ENDFOR PRINT sum Trace: after i=1, sum=1; i=2, sum=3; i=3, sum=6; continuing to i=10 gives sum=55. The loop runs 10 times. If it ended at 9, the result would be 45. Initialising sum to 0 is essential; otherwise the result depends on an unknown old value.
Traps
- Using = instead of == in a condition.
- Forgetting to update the loop variable creates an infinite loop.
- A semicolon after for(...) or if(...) creates an empty body.
- Mixing integer and real division gives unexpected truncation.
- Not initialising a counter or accumulator produces garbage results.
- A switch case needs break where fall-through is not intended.