Unit 5: Digital Development Practice – Building a Solution

Welcome to Building a Solution! In this chapter, we take all our plans, algorithms, and designs and turn them into real, working computer programs. Whether you are creating a simple calculator, an interactive game, or a school database system, this unit gives you the essential programming tools to make it happen.
Don't worry if programming feels tricky at first. Coding is just like learning a new language or following a recipe: once you know the basic ingredients and steps, you can build almost anything!

---

1. Variables, Constants, and Data Types

Every program needs to store and process data. Think of a computer's memory as a giant wall of storage boxes. To use these boxes, we need to label them and choose the right shape for what we want to store.

Variables vs. Constants

• Variables: Memory locations whose values can change while the program is running. For example, a player's score in a game starts at \(0\) and increases as they play: \(score = score + 10\).
• Constants: Memory locations whose values remain fixed and cannot be changed while the program runs. For example, the rate of VAT: \(VAT\_RATE = 0.20\) or the value of Pi: \(\pi = 3.14159\). Using constants prevents accidental changes to critical values and makes code easier to update.

Fundamental Data Types

Choosing the correct data type is essential to prevent errors and save computer memory:

• Integer: Whole numbers with no decimal point (positive, negative, or zero).
Examples: \(-5\), \(0\), \(14\), \(100\)
Real-world use: Counting the number of students in a class or a player's lives in a game.

• Real / Float: Numbers that include a fractional or decimal part.
Examples: \(3.14\), \(-0.75\), \(19.99\)
Real-world use: Storing temperatures, item prices, or running times.

• Character: A single alphanumeric character, symbol, or space enclosed in quotes.
Examples: 'A', '9', '%', ' '
Real-world use: Selecting a menu choice like 'Y' or 'N', or recording a grade.

• String: A sequence of characters of any length.
Examples: "Hello World", "BT48 7NN", "user_123"
Real-world use: Storing names, addresses, and messages.

• Boolean: Can only hold one of two possible values: True or False.
Examples: True, False (often stored internally as \(1\) and \(0\))
Real-world use: Tracking whether a user is logged in or if a game is over.

Did you know? Even if a telephone number or postal code contains numbers, we store it as a String. Why? Because we do not perform mathematical calculations on phone numbers, and strings preserve leading zeros (like in "02890...")!

Quick Review: Variables can change; constants stay the same. Always pick the data type that best matches your data to avoid memory waste and bugs.

---

2. The Three Core Programming Constructs

Every program in the world, no matter how complex, is built from three basic structures: Sequence, Selection, and Iteration.

Memory Trick (SSI): Think of building a program like baking a cake:
1. Sequence = Follow the steps in order.
2. Selection = Choose chocolate or vanilla frosting.
3. Iteration = Stir the batter until smooth!

1. Sequence

Instructions are executed strictly in the order they are written, from top to bottom, one after another.
Example:
\(1.\) Ask user for their name.
\(2.\) Read user input.
\(3.\) Print greeting with the user's name.

2. Selection

Selection allows the program to make decisions and choose different paths of execution based on whether a condition is true or false.

• IF... THEN... ELSE: Used to check conditions.
Example:
IF \(score \ge 50\) THEN
    OUTPUT "Pass"
ELSE
    OUTPUT "Needs Improvement"
ENDIF

• CASE / SELECT: Ideal when comparing a single variable against multiple specific options. It is cleaner and easier to read than many nested IF statements.
Example: Choosing options from a main menu (\(1\) = Play, \(2\) = Settings, \(3\) = Exit).

3. Iteration (Loops)

Iteration repeats a block of code multiple times, saving the programmer from writing repetitive code.

• Count-Controlled Loop (FOR loop): Repeats a fixed, predetermined number of times.
Example: FOR \(i = 1\) TO \(10\) \(\dots\) NEXT \(i\) (executes exactly \(10\) times).

• Condition-Controlled Loop (WHILE loop): Evaluates a condition before each pass and continues repeating as long as the condition remains True. If the condition is false at the start, it may not run at all.
Example: WHILE \(password \neq "secret"\) DO \(\dots\) ENDWHILE

• Condition-Controlled Loop (DO-WHILE / REPEAT-UNTIL): Evaluates the condition after running the block of code, ensuring that the loop body executes at least once.

Key Takeaway: Sequence runs lines in order, Selection chooses a path, and Iteration repeats code.

---

3. Operators in Programming

Operators allow programs to calculate values, compare data, and evaluate conditions.

Arithmetic Operators

• Addition: \(a + b\)
• Subtraction: \(a - b\)
• Multiplication: \(a * b\)
• Division: \(a / b\)
• Integer Division (DIV): Divides two numbers and discards the remainder, returning only the whole number part. For example, \(14 \text{ DIV } 4 = 3\).
• Modulus (MOD / %): Divides two numbers and returns only the remainder. For example, \(14 \text{ MOD } 4 = 2\).

Handy MOD Tip: To test if a number \(n\) is even, check if \(n \text{ MOD } 2 = 0\). If the remainder is \(0\), it's even; if \(1\), it's odd!

Relational (Comparison) Operators

These compare two values and evaluate to either True or False:

• Equal to: \(=\) or \(==\)
• Not equal to: \(\neq\) or \(<>\) or \(!=\)
• Less than: \(<\)
• Greater than: \(>\)
• Less than or equal to: \(\le\) or \(<=\)
• Greater than or equal to: \(\ge\) or \(>=\)

Logical (Boolean) Operators

These combine multiple conditions:

• AND: Returns True only if all conditions are true. (e.g., \(age \ge 17 \text{ AND } passedTest = \text{True}\))
• OR: Returns True if at least one condition is true. (e.g., \(card = \text{True} \text{ OR } cash = \text{True}\))
• NOT: Reverses the boolean state. (e.g., \(\text{NOT}(gameOver)\) turns False into True).

---

4. Data Structures: Arrays

Imagine having to store the names of \(30\) pupils. Creating \(30\) separate variables (\(name1, name2, \dots, name30\)) would be messy and inefficient. Instead, we use an Array.

An Array is an ordered collection of data elements of the same data type stored under a single identifier name.

One-Dimensional (1D) Arrays

Think of a 1D array like a single row of numbered lockers. Each locker holds one value, accessed by its index number.

Example: An array called \(scores\):
• \(scores[0] = 45\)
• \(scores[1] = 78\)
• \(scores[2] = 92\)
• \(scores[3] = 63\)

Common Mistake to Avoid: Most programming languages use zero-based indexing, meaning the first item is at index \(0\), not \(1\). In an array of size \(5\), the indices are \(0, 1, 2, 3, 4\).

Two-Dimensional (2D) Arrays

A 2D array is like a spreadsheet table made up of rows and columns. We access elements using two coordinates: \([row, column]\).
Real-world use: Seating charts, game boards (like Tic-Tac-Toe or Chess), and timetables.

Key Takeaway: Arrays group related data items of the same type together, allowing us to easily process large amounts of data using loops.

---

5. Modular Programming: Functions and Procedures

As programs grow, writing all your code in one long file becomes confusing. Modular programming means breaking a large problem down into smaller, self-contained, manageable blocks of code called Subroutines.

Benefits of Modular Code:

• Makes code easier to read, understand, and maintain.
• Code can be reused multiple times without rewriting it.
• Different programmers can work on separate modules simultaneously.
• Testing and debugging become much simpler.

Procedures vs. Functions

Both are subroutines, but they have one key difference:

• Procedure: A subprogram that performs a specific task and does not return a value back to the main program.
Example: A procedure that clears the screen or displays a welcome banner: displayWelcome().

• Function: A subprogram that executes a calculation or task and returns a single value back to where it was called.
Example: A function that calculates tax and returns the total: \(total = calculateTax(price, rate)\).

Parameters and Arguments

• Parameters: The placeholder variable names defined in the subroutine header to receive input data.
• Arguments: The actual values passed into the subroutine when it is called.

Variable Scope: Local vs. Global

• Local Variables: Declared inside a specific subroutine. They can only be accessed within that subroutine and are destroyed once it finishes running. They keep subroutines independent and prevent accidental data changes elsewhere.
• Global Variables: Declared in the main program and accessible from anywhere throughout the entire program.

---

6. String Manipulation

Programs often need to inspect and modify text. Common string operations include:

• Length: Returns the total number of characters in a string. E.g., \(LEN("Belfast") = 7\).
• Concatenation: Joining two or more strings together end-to-end. E.g., \("Digital" + " " + "Technology"\) becomes "Digital Technology".
• Substring (Slicing): Extracting a smaller portion from a string. E.g., extracting the first \(3\) letters of "Northern Ireland" gives "Nor".
• Case Conversion: Converting characters to UPPERCASE or lowercase. This is useful for standardising input before checking conditions.

---

7. Finding and Handling Errors

Errors in programming are called bugs. To build a robust solution, you must be able to recognise and fix the three main types of errors:

1. Syntax Errors

• What it is: Mistakes in the grammar or rules of the programming language.
• When it happens: Detected before or during compilation; the program will not run.
• Examples: Spelling a keyword wrong (e.g., PIRNT instead of PRINT), missing quotation marks, or unclosed brackets.

2. Runtime Errors

• What it is: An error that causes the program to crash abruptly while it is running, even though the syntax is correct.
• Examples: Dividing a number by zero (\(x / 0\)), running out of memory, or attempting to open a file that does not exist.

3. Logic Errors

• What it is: The program runs without crashing, but produces incorrect, unexpected results because the underlying algorithm or calculation is wrong.
• Examples: Writing \(area = length + width\) instead of \(area = length * width\), or using \(>\) instead of \(<\).

Summary Comparison Table:

• Syntax Error: Violates language rules \(\rightarrow\) Program fails to compile/run.
• Runtime Error: Illegal operation at run-time \(\rightarrow\) Program crashes unexpectedly.
• Logic Error: Flawed program logic \(\rightarrow\) Program runs fine, but output is wrong.

---

8. User Interface (UI) Design and Defensive Design

When developing the front end of your digital solution, the user interface must be intuitive, accessible, and resilient to mistakes.

Key Principles of Good User Interface Design:

• Consistency: Use standard fonts, button styles, colour schemes, and navigation throughout the application.
• Clear Feedback: Give prompt visual or audio feedback when actions happen (e.g., "File successfully saved!" or a loading progress bar).
• Accessibility: Provide suitable colour contrast, adjustable text sizes, and screen-reader compatibility for users with visual impairments.
• Appropriate Controls: Use drop-down lists, radio buttons, and checkboxes to simplify user input and minimise typing mistakes.

Defensive Programming

Defensive programming is the practice of designing code to handle unexpected user actions without crashing.

• Input Validation: Automated checks that inspect data as it is entered to ensure it is sensible and follows required rules (e.g., Range checks, Type checks, Length checks, and Presence checks).
• Input Sanitisation: Cleaning up input by removing unwanted spaces or dangerous characters before processing.

Final Tip for Success: Always test your solution systematically with normal, boundary, and erroneous data to ensure every single path and subroutine works exactly as designed!