Welcome to Programming Concepts!
Hello future programmers! This chapter is where the fun truly begins. We are moving from understanding how computers work (Hardware and Data) to giving them specific, step-by-step instructions—which is what programming is all about!
Learning these fundamental concepts will allow you to design, write, and understand any algorithm, preparing you perfectly for the practical problem-solving questions in Paper 2. Don't worry if the code looks strange at first; we will break everything down into manageable pieces. Let’s get started!
8.1 Programming Concepts: The Building Blocks
8.1.1 Variables and Constants
Think of variables and constants as named storage boxes inside the computer's memory.
Variables
A variable is a memory location used to store a value that can change during the execution of a program.
Example: A player's Score will change as they play the game.
Constants
A constant is a memory location used to store a value that cannot change during the execution of a program.
Example: The value of Pi (\(\pi\)) or a fixed TaxRate.
In pseudocode, we use keywords to declare them:
- Variable Declaration:
DECLARE TotalScore : INTEGER - Constant Declaration:
CONSTANT MaxAttempts ← 3 - Assignment: We use the assignment operator
←to put a value into a variable.
TotalScore ← 100
8.1.2 Basic Data Types
When you declare a variable or constant, you must tell the computer what type of data it will hold. This helps the computer allocate the correct amount of memory and prevents mistakes.
Analogy: A data type is like labelling a container—if the label says 'Water', you don't try to store electricity in it!
The basic data types you must know are:
- INTEGER: A whole number (positive, negative, or zero). No decimal places.
Literals: 5, -100, 0 - REAL: A number that can contain a fractional part (decimals).
Literals: 3.14, -0.5, 4.0 - CHAR (Character): A single letter, number, or symbol. Enclosed in single quotes.
Literals: 'A', '7', '@' - STRING: A sequence of characters (text). Enclosed in double quotes.
Literals: "Hello World", "CS0478" - BOOLEAN: A logical value that can only be TRUE or FALSE.
Literals: TRUE, FALSE
If you are storing someone's age, use INTEGER. If you are storing their name, use STRING. If you are checking if a light is ON or OFF, use BOOLEAN.
8.1.3 Input and Output (I/O)
Programs need to interact with the user. This is handled by I/O commands.
- INPUT: Reads data from the user (usually the keyboard) and stores it in a variable.
Syntax: INPUT
Example: INPUT UserName - OUTPUT: Displays data or messages to the user (usually the screen).
Syntax: OUTPUT
Example: OUTPUT "Hello, ", UserName
8.1.4 (f) Operators
Operators are special symbols used to perform calculations or comparisons.
Arithmetic Operators (Calculation)
These are used to perform mathematical operations:
- + (Addition)
- - (Subtraction)
- * (Multiplication)
- / (Division, results in REAL)
- ^ (Raised to the power of, e.g., \(2^3\))
- DIV: Integer Division (returns the quotient, discards the remainder).
Example: DIV(10, 3) returns 3 - MOD: Modulus (returns the remainder after integer division).
Example: MOD(10, 3) returns 1
Memory Aid: MOD is the remainder or "leftovers" after dividing. DIV is how many times it goes in fully.
Relational Operators (Comparison)
These compare two values and always return a BOOLEAN result (TRUE or FALSE).
- = (Equal to)
- < (Less than)
- <= (Less than or equal to)
- > (Greater than)
- >= (Greater than or equal to)
- <> (Not equal to)
Logical Operators (Combining Conditions)
These are used to combine multiple Boolean conditions.
- AND: Result is TRUE only if ALL conditions are TRUE.
- OR: Result is TRUE if AT LEAST ONE condition is TRUE.
- NOT: Reverses the condition (TRUE becomes FALSE, FALSE becomes TRUE).
Example: IF (Age > 18) AND (IsCitizen = TRUE) THEN...
8.1.4 Control Structures: Sequence, Selection, Iteration
(a) Sequence
Sequence is the simplest control structure. Instructions are executed one after the other, in the order they appear. This is the default flow of a program.
Example:
1. Total ← 0
2. Number1 ← 10
3. Total ← Total + Number1
(b) Selection (Decision Making)
Selection allows the program to choose which block of code to execute based on a condition (a Boolean test).
IF Statements
Used for one or two possible outcomes:
IF <condition> THEN
<statements>
ELSE
<statements>
ENDIF
CASE Statements
Used when there are many possible outcomes based on a single variable's value.
INPUT Grade
CASE OF Grade
'A' : OUTPUT "Excellent"
'B' : OUTPUT "Good"
OTHERWISE OUTPUT "Needs Improvement"
ENDCASE
Nested Statements (8.1.5)
A nested statement is a selection or iteration structure placed entirely inside another one. This is essential for complex logic.
You will not be required to write more than three levels of nested statements in the exam.
Example of nested IF:
IF Score > 50 THEN
IF Score > 90 THEN // Nested IF
OUTPUT "Top result!"
ELSE
OUTPUT "Pass"
ENDIF
ELSE
OUTPUT "Fail"
ENDIF
(c) Iteration (Looping)
Iteration means repeating a block of code multiple times. There are three main types:
1. Count-Controlled Loop (FOR)
Used when you know exactly how many times the loop should run.
- It automatically initializes, checks, and increments (or decrements) a counter variable.
FOR Counter ← 1 TO 10
OUTPUT "Loop number: ", Counter
NEXT Counter
2. Pre-Condition Loop (WHILE)
The condition is tested before the loop runs. If the condition is initially FALSE, the code inside the loop will never execute (zero times).
WHILE <condition> DO
<statements>
ENDWHILE
3. Post-Condition Loop (REPEAT UNTIL)
The condition is tested after the loop runs. This guarantees that the code inside the loop will execute at least once. The loop continues UNTIL the condition becomes TRUE.
REPEAT
<statements>
UNTIL <condition>
Common Mistake Alert: WHILE loops run as long as the condition is TRUE. REPEAT UNTIL loops run UNTIL the condition becomes TRUE (i.e., as long as it is FALSE).
8.1.4 (d, e) Totalling, Counting, and String Handling
(d) Totalling and Counting
These are two common patterns used inside loops:
- Counting: Keeping track of how many times something happens. You typically initialise the count variable to 0 and add 1 each time the event occurs.
Example: NumberOfStudents ← NumberOfStudents + 1 - Totalling (Accumulation): Keeping a running total of values. You typically initialise the total variable to 0 and add the new value each time.
Example: TotalSales ← TotalSales + CurrentSaleValue
(e) String Handling
These are standard functions used to manipulate text (STRING data).
- LENGTH(
): Returns the number of characters in the string.
Example: LENGTH("Cat") returns 3. - LCASE(
): Converts the string or character to lower case. - UCASE(
): Converts the string or character to UPPER CASE. - SUBSTRING(
, Returns a section of the string. You need to specify the starting position and how many characters to include., ):
Note: Pseudocode often uses a starting position of 1 for the first character, but the syllabus confirms 0 or 1 may be used in programming systems. Stick to the convention used in your question or 1 if unspecified.
Example: SUBSTRING("Program", 3, 4) returns "ogra".
8.1.6 Procedures, Functions, and Variables Scope
As programs get larger, we break them down into smaller, reusable blocks of code.
Procedures and Functions
Both Procedures and Functions are reusable sub-programs, but they have one key difference:
- Procedure: A named block of code that performs a task but does not return a value. It is called using the CALL keyword.
Example: CALL DisplayMenu() - Function: A named block of code that performs a task and must return a single value to the point where it was called. It is used as part of an expression.
Example: Area ← CalculateArea(5, 10)
Parameters
Parameters are values passed into a procedure or function so that the sub-program can use them. They act like inputs to the sub-program.
// Definition of a procedure with one parameter
PROCEDURE Line(Size : INTEGER)
// ... statements using Size ...
ENDPROCEDURE
// Calling the procedure
CALL Line(60)
You may deal with procedures and functions with up to three parameters.
Local and Global Variables
Scope refers to the area of the program where a variable is accessible.
- Global Variable: Declared at the very start of the program (main code body). It can be accessed and modified anywhere in the program, including inside procedures and functions.
- Local Variable: Declared inside a specific procedure or function. It can only be used within that sub-program. Once the sub-program finishes, the local variable is destroyed.
It's like having a secret temporary note pad only you can read.
Why use Local Variables? They prevent accidental interference. If two different procedures use a variable named i, they won't clash if i is declared locally in both.
8.1.7 Library Routines and 8.1.8 Maintainable Programs
8.1.7 Library Routines
These are pre-written functions that are included in the programming environment, saving you time. The main ones you need to know (apart from string functions, MOD, and DIV) are:
- ROUND(
, Rounds a REAL number to a specified number of decimal places.):
Example: ROUND(3.14159, 2) returns 3.14 - RANDOM(): Returns a random REAL number between 0 and 1 (inclusive).
To generate a random integer between 1 and 10: Value ← ROUND (RANDOM() * 10, 0)
8.1.8 Creating a Maintainable Program
A maintainable program is one that is easy for someone else (or yourself later) to understand, debug, and update.
Key features include:
- Meaningful Identifiers: Use descriptive names for variables, constants, procedures, and functions (e.g., MaximumScore instead of MS).
- Commenting: Using // to add notes explaining what the code does, especially complex parts.
- Use of Procedures and Functions: Breaking the code into logical sub-sections makes the main program flow cleaner.
8.2 Arrays: Storing Lists of Data
8.2.1 Declaration and Use of Arrays
An array is a data structure used to store a fixed number of items of the same data type, accessed using an index (a number).
Analogy: An array is like a row of identical mailboxes, each numbered sequentially.
1. One-Dimensional (1D) Arrays
A 1D array is a simple list or vector.
Declaration:
DECLARE StudentNames : ARRAY[1:30] OF STRING // 30 elements, indexed 1 to 30
Usage: Elements are accessed using square brackets [ ].
StudentNames[1] ← "Ali" // Puts "Ali" in the first position OUTPUT StudentNames[5] // Outputs the value at position 5
2. Two-Dimensional (2D) Arrays
A 2D array is a list of lists, often visualised as a table or grid (rows and columns).
Declaration:
DECLARE Board : ARRAY[1:3, 1:3] OF CHAR // A 3x3 grid (like Noughts and Crosses)
Usage: The first index is usually the Row, and the second is the Column.
Board[2, 3] ← 'X' // Puts 'X' in Row 2, Column 3
8.2.2 & 8.2.3 Using Arrays with Iteration
Since array indices are consecutive numbers, arrays are almost always processed using iteration (loops), especially the FOR loop.
This allows you to read or write values to every element systematically.
// Writing values into an array (reading from user input)
FOR Index ← 1 TO 30
INPUT StudentNames[Index]
NEXT Index
// Reading values from a 2D array (requires nested iteration)
FOR Row ← 1 TO 3
FOR Column ← 1 TO 3
OUTPUT Board[Row, Column]
NEXT Column
NEXT Row
8.3 File Handling: Permanent Storage
8.3.1 Purpose of Files
When a program runs, variables are stored in temporary RAM (main memory). When the program closes, this data is lost.
The purpose of storing data in a file is to keep the data permanently (on secondary storage like a hard disk) so it can be retrieved the next time the program runs.
8.3.2 File Operations
To work with files in pseudocode, you must follow specific steps:
Step 1: OPEN the file
- You must specify the mode: FOR READ (to read existing data) or FOR WRITE (to create a new file or overwrite an existing one).
OPENFILE "Scores.txt" FOR READ
Step 2: READ or WRITE data
- READFILE: Reads a single item of data or a line of text from the file and puts it into a variable.
READFILE "Scores.txt", PlayerName // Reads one item/line into PlayerName
WRITEFILE "Scores.txt", NewScore
Step 3: CLOSE the file
- When you are finished, you must CLOSE the file to ensure all data is saved correctly and the file is no longer blocked from use by other programs.
CLOSEFILE "Scores.txt"