Welcome to Programming Constructs
Welcome to one of the most exciting parts of Digital Technology! Have you ever wondered how video games know when you have won, or how a smartphone knows to unlock when you enter the correct passcode? It all comes down to programming constructs.
Programming constructs are the fundamental building blocks used to write any computer program. Think of them like LEGO bricks: on their own, each brick is very simple, but when you connect them together in different ways, you can build anything from a simple calculator to a massive multiplayer game.
Don't worry if programming seems confusing at first! In this guide, we will break every concept down into small, easy-to-understand steps with everyday examples.
---1. The Three Fundamental Constructs
Every single program ever written—no matter how simple or complex—is built using three basic control structures:
1. Sequence
2. Selection
3. Iteration
Memory Trick: Remember the letters S-S-I ("Super Smart Individuals") to recall the three core building blocks!
A. Sequence
Sequence means executing instructions in order, one after the other, from top to bottom. The computer must finish one step before moving on to the next.
Everyday Analogy: Making a bowl of cereal.
1. Get a bowl out of the cupboard.
2. Pour cereal into the bowl.
3. Pour milk over the cereal.
If you change the order (such as pouring the milk before getting the bowl), you will make a huge mess! Computers work the exact same way—order matters.
B. Selection
Selection allows a program to make a decision based on whether a condition is True or False. This enables the program to take different paths.
Everyday Analogy: Deciding what to wear.
IF it is raining outside, THEN take an umbrella, ELSE wear sunglasses.
C. Iteration
Iteration means repeating a block of code multiple times. In programming, we often call this looping.
Everyday Analogy: Doing 10 star jumps in PE.
Instead of someone shouting "Do a star jump!" 10 separate times, they tell you: "Repeat star jump 10 times."
Key Takeaway: Sequence runs step-by-step; Selection makes a choice; Iteration repeats instructions.
---2. Storing Data: Variables and Constants
Before a program can make decisions or repeat actions, it needs a way to remember information.
Variables
A variable is a named memory location used to store data that can change while the program is running.
Real-World Example: The score in a football match. It starts at \(0\), changes to \(1\), then \(2\), and so on as the game progresses.
Constants
A constant is a named memory location used to store data that remains the same and cannot be altered while the program is running.
Real-World Example: The value of Pi (\(\pi \approx 3.14159\)), or the number of days in a week (\(7\)).
Why use Constants instead of Variables?
• Prevents Accidental Changes: It ensures critical values (like tax rates or speed limits) are not accidentally altered elsewhere in the code.
• Easier Updates: If a constant value changes in the future (for example, VAT changing from \(20\%\) to \(22\%\)), you only need to change it in one place at the top of your program.
Common Data Types
Computers store different types of data in different ways:
• Integer: Whole numbers without decimals (e.g., \(15\), \(-3\), \(0\)).
• Real / Float: Numbers with a decimal point (e.g., \(19.99\), \(-2.5\)).
• Char / Character: A single letter, number, or symbol (e.g., 'A', '?', '4').
• String: A sequence of characters/text enclosed in speech marks (e.g., "Belfast", "GCSE123").
• Boolean: Can only hold one of two values: True or False (e.g., isGameOver = False).
Key Takeaway: Variables change during execution; Constants remain fixed throughout.
---3. Operators in Programming
Operators are special symbols used to perform calculations, compare values, or make logical decisions.
Arithmetic Operators
Used to carry out mathematical calculations:
• Addition: \(+\) (e.g., \(5 + 3 = 8\))
• Subtraction: \(-\) (e.g., \(10 - 4 = 6\))
• Multiplication: \(*\) (e.g., \(4 * 3 = 12\))
• Division: \(/\) (e.g., \(10 / 2 = 5\))
• MOD (Modulus / Remainder): Finds the remainder after division (e.g., \(10 \text{ MOD } 3 = 1\), because \(3\) goes into \(10\) three times with a remainder of \(1\)).
• DIV (Integer Division): Finds the whole number part of division and ignores the remainder (e.g., \(10 \text{ DIV } 3 = 3\)).
Relational / Comparison Operators
Used to compare two values, producing a True or False result:
• Equal to: \(==\) or \(=\) (e.g., \(x == 5\))
• Not equal to: \(!=\) or \(<>\) (e.g., \(x \neq 5\))
• Greater than: \(>\) (e.g., \(age > 17\))
• Less than: \(<\) (e.g., \(score < 50\))
• Greater than or equal to: \(\ge\) (e.g., \(mark \ge 60\))
• Less than or equal to: \(\le\) (e.g., \(attempts \le 3\))
Logical / Boolean Operators
Used to combine multiple conditions:
• AND: Returns True only if both conditions are True (e.g., IF age \(\ge\) 17 AND hasPassedTest == True).
• OR: Returns True if at least one condition is True (e.g., IF day == "Saturday" OR day == "Sunday").
• NOT: Reverses the condition; turns True to False and False to True (e.g., IF NOT isRaining).
Key Takeaway: Arithmetic operators calculate values; Relational operators compare them; Logical operators combine conditions.
---4. Selection Structures in Detail
Selection allows programs to be dynamic by reacting differently to different user inputs.
IF... THEN... ELSE Statements
This is the most common way to make decisions in code.
Example:
IF score \(\ge\) 50 THEN
OUTPUT "You passed!"
ELSE
OUTPUT "Please try again."
END IF
Nested IF Statements
A Nested IF occurs when an IF statement is placed inside another IF statement. This is useful when you need to test multiple levels of conditions.
Example: Checking access to a game ride:
IF height \(\ge\) 140 THEN
IF age \(\ge\) 12 THEN
OUTPUT "Access granted."
ELSE
OUTPUT "Too young for this ride."
END IF
ELSE
OUTPUT "Too short for this ride."
END IF
CASE / SELECT CASE Statements
When you have a single variable that could match many different values (like a menu selection), writing dozens of IF statements can make code messy and hard to read. A CASE statement is much cleaner.
Example:
SELECT CASE choice
CASE 1: OUTPUT "Play Game"
CASE 2: OUTPUT "Load Game"
CASE 3: OUTPUT "Game Options"
CASE ELSE: OUTPUT "Invalid choice!"
END SELECT
Common Mistake to Avoid: Don't use a long chain of 10 IF-ELSE statements for a simple menu when a CASE statement makes the program much easier to read and maintain!
Key Takeaway: Use IF-THEN-ELSE for basic true/false decisions and CASE when checking a single variable against multiple options.
---5. Iteration Structures (Loops)
In programming, doing the same task over and over manually is inefficient. We use two main categories of loops:
A. Count-Controlled Loops (FOR Loops)
A count-controlled loop repeats a set of instructions a fixed, known number of times before it starts.
Example: Printing numbers 1 to 5.
FOR count = 1 TO 5
OUTPUT count
NEXT count
When to use: Use a FOR loop when you know exactly how many times the loop needs to run (e.g., printing 30 student names, looping through 7 days of the week).
B. Condition-Controlled Loops
A condition-controlled loop repeats instructions until a specific condition changes. You use this when you do not know in advance how many times the loop will need to repeat.
1. Pre-Condition Loop (WHILE... DO / WHILE... ENDWHILE)
• The condition is checked at the start before the code inside runs.
• If the condition is False right away, the code inside might never run.
Example:
WHILE batteryLevel \(> 0\) DO
OUTPUT "Phone is running..."
batteryLevel = batteryLevel - 1
END WHILE
2. Post-Condition Loop (REPEAT... UNTIL / DO... WHILE)
• The condition is checked at the end after the code has run.
• The code inside is guaranteed to run at least once.
Example: Entering a password:
REPEAT
OUTPUT "Enter your password:"
password = USERINPUT
UNTIL password == "Secret123"
Quick Comparison Table
• FOR Loop: Known number of repetitions | Checked by counter.
• WHILE Loop: Unknown number of repetitions | Checked at start (may run \(0\) times).
• REPEAT-UNTIL: Unknown number of repetitions | Checked at end (always runs at least \(1\) time).
Key Takeaway: Use FOR when you know the count. Use WHILE if the loop might not need to run at all. Use REPEAT... UNTIL if the loop must execute at least once.
---6. Subroutines: Procedures and Functions
As programs grow, they can become thousands of lines long. Writing everything in one huge block makes code difficult to read, test, and fix. To solve this, we break code down into smaller, reusable blocks called subroutines.
What is a Subroutine?
A subroutine is a self-contained block of code that performs a specific task and can be called by name from anywhere in the main program.
Procedures vs. Functions
• Procedure: A subroutine that carries out a set of instructions, but does not return a value back to the main program (e.g., displaying a welcome message or clearing the screen).
• Function: A subroutine that performs a calculation or task and always returns a single value back to the main program (e.g., calculating the area of a circle or generating a random number).
Parameters and Arguments
• Parameter: A variable defined in the subroutine header to receive data passed into it.
• Argument: The actual value that is passed into the subroutine when it is called.
Example:
FUNCTION calculateArea(width, height) // width and height are parameters
area = width * height
RETURN area
END FUNCTION
Calling the function in the main program: total = calculateArea(5, 10) // 5 and 10 are arguments
Benefits of Modular Programming (Using Subroutines)
1. Code Reusability: You write the code once and can use it multiple times across the program without rewriting it.
2. Easier Debugging: It is much simpler to test and fix a small \(10\)-line subroutine than a massive \(1000\)-line program.
3. Team Collaboration: Different programmers in a team can work on separate subroutines at the same time.
4. Improved Readability: The main program becomes cleaner and easier to understand.
Key Takeaway: Procedures perform actions; Functions return values. Both make programs modular, clean, and reusable.
---Quick Exam Review
Before your exam, make sure you can answer these quick check questions:
• Can you identify the 3 fundamental programming constructs? (Sequence, Selection, Iteration)
• Can you explain the difference between a variable and a constant? (Variables change; constants stay the same)
• Do you know what \(14 \text{ MOD } 4\) equals? (Answer: \(2\), because \(4 \times 3 = 12\) with \(2\) left over)
• Can you state whether a WHILE loop or REPEAT-UNTIL loop runs at least once? (REPEAT-UNTIL always runs at least once)
• What is the main difference between a Procedure and a Function? (A Function returns a value; a Procedure does not)