Programming Concepts and Practical Coding: Variables, Control, Subprograms and Files
Programming concepts and practical coding turns algorithms into working programs: variables and constants, data types, control structures, subprograms, file handling and basic array and string processing. Questions ask you to write short code, predict output, and explain why a program fails.
Variables, constants and types
A variable is a named store whose value can change; a constant is fixed at declaration and protects against accidental change. Data types: integer, real, character, string, Boolean and date. Use meaningful names, initialise accumulators to 0 and counters to 0 or 1, and pick the type that fits the data - storing a score as a string prevents arithmetic on it.
Control structures and scope
Selection: IF…ELSE, CASE. Iteration: FOR (count controlled), WHILE (test at the top), REPEAT…UNTIL (test at the bottom). Scope: a local variable exists only inside its subprogram; a global variable is visible throughout, which makes programs harder to debug. Pass values into subprograms as parameters; a function returns a value, a procedure does not.
Subprograms and parameter passing
By value: the subprogram receives a copy, so changes do not affect the caller's variable. By reference: the subprogram receives the address, so changes persist. Use functions for calculations (average, tax) and procedures for actions (print a report, update a file).
File handling
Open the file with a mode (read, write, append), read or write records in a loop until end-of-file, then close it. Closing flushes buffers and releases the file; forgetting it can lose data. Sequential files suit reports; random-access files allow a record to be read directly by its key.
Worked example
PROCEDURE AddOne(BYREF n) n ← n + 1 ENDPROCEDURE x ← 5 AddOne(x) OUTPUT x
Because n is passed by reference, n and x share the same storage, so n ← n + 1 changes x to 6 and the output is 6. If the parameter were BYVAL, n would be a copy and the output would stay 5. State the mechanism, not just the number.
Traps
= assigns while == compares, and mixing them can make a condition always true. An uninitialised total holds garbage, not zero. Local variables cease to exist once the subprogram returns. Array subscripts start at 0 in many languages but at 1 in pseudocode - check the convention given. Integer division truncates, so 7/2 gives 3 in an integer context.