📑 Contents

Chapter 11.1: Programming Basics

Variables, Constants, Operators & Library Routines

9618 AS Computer Science

📚 Learning Objectives
📖 Prior Knowledge Required
🌟 Did You Know?

Variables are called identifiers because they identify a storage location in memory. When you create a variable named "Age", the computer reserves a specific memory location and uses "Age" as a label to find it quickly!

1. Variables

📖 Definition: Variable

A variable is an identifier that can change in the lifetime of a program. It is a container for storing data values with a name that can change during the execution of a program.

In programming, we need to DECLARE variables (also called identifiers). When a variable is declared, memory is allocated based on the data type indicated.

1.1 Identifier Naming Rules

⚠️ Important: Identifier Rules

1.2 Declaring Variables in Pseudocode

📝 Pseudocode Syntax
DECLARE <identifier> : <datatype>

To declare a variable, use the keyword DECLARE followed by the name and data type:

DECLARE Age : INTEGER DECLARE Name : STRING DECLARE IsLoggedIn : BOOLEAN DECLARE Temperature : REAL DECLARE DOB : DATE

1.3 Assigning Values

You can assign a value using the assignment operator ←:

Age ← 18 Name ← "Alice" IsLoggedIn ← TRUE Temperature ← 36.5
18 Age Memory Location Identifier (Name) Variable = Named Memory Location

2. Constants

📖 Definition: Constant

A constant is an identifier set once in the lifetime of a program. It is a location in memory where data is stored that cannot be changed while the program is running.

⚠️ Key Characteristics of Constants

2.1 Declaring Constants in Pseudocode

📝 Pseudocode Syntax
CONSTANT <identifier> ← <value>

To declare a constant, use the keyword CONSTANT:

CONSTANT Pi ← 3.14159 CONSTANT MaxScore ← 100 CONSTANT SchoolName ← "Meridian Academy"

2.2 Example: Using Constants

Example: Calculating the area of a circle using the formula: Area ← π × radius²
CONSTANT Pi ← 3.14159 DECLARE Radius : REAL DECLARE Area : REAL OUTPUT "Enter the radius of the circle:" INPUT Radius Area ← Pi * Radius * Radius OUTPUT "The area of the circle is: ", Area

2.3 Variables vs Constants Comparison

Feature Variable Constant
Value Change Can change during program execution Cannot change once set
Naming Convention Pascal case (e.g., TotalScore) UPPERCASE (e.g., MAX_SCORE)
Declaration Keyword DECLARE CONSTANT
Memory Allocation Allocated when declared Allocated when declared
Use Case Storing changing data (counters, inputs) Fixed values (π, max values, settings)

3. Variables & Constants in Different Languages

3.1 Language Comparison Table

Feature Python VB.NET Java
Declare variable Just assign it (no keyword needed) Dim radius As Double double radius;
Assign variable radius = 5 radius = 5 radius = 5;
Declare constant PI = 3.14159 (convention: UPPERCASE) Const Pi As Double = 3.14159 final double PI = 3.14159;
Reassign constant? Yes (not truly constant unless enforced) Cannot change once set Cannot change once set
Use in calculation area = PI * radius * radius area = Pi * radius * radius area = PI * radius * radius;

3.2 Python-Specific Features

📖 Python Variable Features
💡 Exam Tip

In pseudocode exams, always use DECLARE for variables and CONSTANT for constants with proper data types. Python conventions don't apply to pseudocode!

3.3 Multiple Assignment in Python

📝 Python Multiple Assignment

Many Values to Multiple Variables:

x, y, z = "Orange", "Banana", "Cherry"

One Value to Multiple Variables:

x = y = z = "Orange"

Unpack a Collection:

fruits = ["apple", "banana", "cherry"] x, y, z = fruits

4. Arithmetic Operators

Arithmetic operators are used to perform basic maths operations in a program. These include adding, subtracting, multiplying and dividing values.

4.1 Common Arithmetic Operators

Operator Purpose Example Result
+ Addition or string concatenation 5 + 3
"John" + " " + "Doe"
8
"John Doe"
- Subtraction 10 - 4 6
* Multiplication 3 * 5 15
/ Division 10 / 2 5
^ Exponentiation (power of) 3 ^ 3 27
MOD Modulus (remainder after division) 10 MOD 3 1

4.2 Operator Precedence (BODMAS / BIDMAS)

⚠️ Important: Order of Operations

Arithmetic operators follow operator precedence. Multiplication and division happen before addition and subtraction unless brackets are used.

result ← 2 + 3 * 4 // gives 14 (multiplication first) result ← (2 + 3) * 4 // gives 20 (brackets first)
B - Brackets O - Orders D - Division M - Multiply A - Add 2 + 3 * 4 = 2 + 12 = 14 (2 + 3) * 4 = 5 * 4 = 20 Brackets change everything!
🧠 Memory Trick: MOD

Think of MOD as "What's left over?" When you divide 10 by 3, you get 3 with remainder 1. That remainder (1) is what MOD gives you!

10 MOD 3 = 1 (because 10 = 3 × 3 + 1)

5. Logical Operators

Logical operators (also called comparison operators) are used to compare values. They return either TRUE or FALSE and are commonly used in conditions and loops.

5.1 Common Logical Operators

Operator Purpose Example Result
= Equal to 5 = 6 FALSE
<> Not equal to 5 <> 7 TRUE
> Greater than 5 > 10 FALSE
< Less than 5 < 10 TRUE
>= Greater than or equal to 5 >= 10 FALSE
<= Less than or equal to 5 <= 10 TRUE

5.2 Example Code

x ← 5 y ← 10 OUTPUT x = y // FALSE OUTPUT x <> y // TRUE OUTPUT x < y // TRUE OUTPUT x > y // FALSE OUTPUT x <= y // TRUE OUTPUT x >= y // FALSE
💡 Exam Tip

In pseudocode, use = for equality comparison (not == like in Python/Java). Use <> for "not equal to" (not != like in many programming languages).

5 (x) 10 (y) x < y is TRUE Comparing Values on Number Line
❌ Common Mistake

Don't confuse = (comparison/equality) with (assignment). In pseudocode:

6. Global and Local Variables

6.1 Global Variables

📖 Definition: Global Variable

Global variables are variables that are created outside of a function. They can be used by everyone, both inside of functions and outside.

⚠️ Important: Variable Scope

If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

6.2 The Global Keyword

📝 Using the global Keyword

Normally, when you create a variable inside a function, that variable is local. To create a global variable inside a function, you can use the global keyword.

Also, use the global keyword if you want to change a global variable inside a function.

GLOBAL SCOPE x = 10 FUNCTION myFunc() x = 5 (local) global x (access global)

6.3 Best Practices

📖 Declaring Variables at Start

It is good practice to declare (set up) your variables at the start of a program. The reason for this is that each time you declare a variable, a part of the computer's memory is reserved for it. Declaring these variables at the start allows the computer to calculate whether or not it actually has enough memory to run the program.

7. Library Routines

📖 Definition: Library Routine

A library routine is a debugged block of code (subroutine, procedure, function, etc.), often designed to handle commonly occurring problems or tasks.

🌟 What are Libraries?

Libraries are a collection of ready-made sub-routines that can be called by programs executing within the host operating system. Library routines are stored in a program library and given names. This allows them to be called into immediate use when needed, even from other programs.

7.1 Benefits of Library Routines

Benefit Explanation
Faster Development Makes writing programs faster as part of the work has already been done
Already Debugged Library routines are tested and debugged, reducing errors in your code
Reusability Same routine can be used by multiple programs
Saves Time No need to reinvent the wheel - common tasks already solved
Consistency Standard routines ensure consistent behavior across programs

7.2 Example: Dynamic Link Libraries (DLL)

Example: When programming in the Windows operating system, you can call Dynamic Link Libraries (DLL). These libraries contain sub-routines written to carry out common tasks in the Windows environment.

For example, a 'Save As' routine where the user needs to save their work as a file. All you need to do in your program is call the appropriate DLL sub-routine with the correct parameters, and the 'Save As' dialogue box appears!
LIBRARY SaveFile() OpenFile() PrintDoc() Program A Program B Program C Multiple programs can use the same library routines
💡 Exam Tip

When asked about library routines, mention: (1) They are pre-written and debugged code, (2) They save development time, (3) They can be reused by multiple programs, (4) Examples include math functions, file handling, and UI routines.

8. Data Types Summary

When a variable is declared, memory is allocated based on the data type indicated. Different data types require different amounts of memory and can store different kinds of values.

8.1 Common Data Types

Data Type Description Example Values
INTEGER Whole numbers (no decimals) 5, -3, 0, 100
REAL Numbers with decimal places 3.14, -2.5, 0.001
STRING Text characters (letters, numbers, symbols) "Hello", "123", "A"
BOOLEAN Logical values (true or false only) TRUE, FALSE
DATE Date values 01/01/2025, 15/06/2024
CHAR Single character 'A', '5', '!'

8.2 Declaration Examples

DECLARE StudentName : STRING // Stores text DECLARE Age : INTEGER // Stores whole number DECLARE Temperature : REAL // Stores decimal number DECLARE IsPassing : BOOLEAN // Stores TRUE or FALSE DECLARE BirthDate : DATE // Stores a date DECLARE Grade : CHAR // Stores single character
INTEGER 42 REAL 3.14 STRING "Hello" BOOLEAN TRUE Different types = Different memory sizes INT: 2-4 bytes REAL: 4-8 bytes STRING: varies

9. Exam-Style Questions (Part 1)

1. Explain the difference between a variable and a constant. Give an example of when you would use each. [4 marks]

Answer:

  • A variable is an identifier whose value can change during program execution
  • A constant is an identifier whose value is set once and cannot change during execution
  • Variables are used for data that changes, e.g., a counter in a loop or user input
  • Constants are used for fixed values, e.g., PI (3.14159) or MAX_SCORE (100)

Additional points for deeper understanding:

  • Constants improve code readability and maintainability
  • Constants prevent accidental modification of important values
2. Write pseudocode to declare a constant for the value of π and a variable for the radius. Then calculate and output the circumference of a circle. [5 marks]

Answer:

CONSTANT Pi ← 3.14159 DECLARE Radius : REAL DECLARE Circumference : REAL OUTPUT "Enter the radius:" INPUT Radius Circumference ← 2 * Pi * Radius OUTPUT "The circumference is: ", Circumference

Marks awarded for:

  • Correct CONSTANT declaration (1 mark)
  • Correct DECLARE statements with data types (1 mark)
  • INPUT statement (1 mark)
  • Correct formula for circumference (1 mark)
  • OUTPUT statement (1 mark)
3. Evaluate the following expressions, showing your working:
a) 3 + 4 * 2
b) (3 + 4) * 2
c) 10 MOD 3
d) 2 ^ 3 + 1 [4 marks]

Answer:

a) 3 + 4 * 2 = 3 + 8 = 11

(Multiplication before addition)

b) (3 + 4) * 2 = 7 * 2 = 14

(Brackets evaluated first)

c) 10 MOD 3 = 1

(10 ÷ 3 = 3 remainder 1)

d) 2 ^ 3 + 1 = 8 + 1 = 9

(Exponentiation before addition)

4. State the naming conventions for identifiers in pseudocode and explain why following conventions is important. [5 marks]

Answer:

Naming conventions:

  • Use Pascal case (mixed case, starting with capital letter)
  • Only contain letters (A-Z, a-z) and digits (0-9)
  • Must start with a capital letter, not a digit
  • No spaces or special characters
  • Constants should be named in UPPERCASE

Importance:

  • Improves code readability and maintainability
  • Helps distinguish between variables and constants
  • Makes code easier to understand and debug
  • Follows standard industry practices
5. Given: x ← 7 and y ← 3, evaluate the following logical expressions:
a) x = y
b) x <> y
c) x > y
d) x <= 7 [4 marks]

Answer:

a) x = y → 7 = 3 → FALSE

b) x <> y → 7 <> 3 → TRUE

c) x > y → 7 > 3 → TRUE

d) x <= 7 → 7 <= 7 → TRUE

Additional points for deeper understanding:

  • <= means "less than or equal to", so 7 <= 7 is TRUE
  • <> is the "not equal to" operator in pseudocode

9. Exam-Style Questions (Part 2)

6. Explain what is meant by a library routine and describe two benefits of using them. [4 marks]

Answer:

A library routine is a debugged block of code (subroutine, procedure, or function) designed to handle commonly occurring problems or tasks. It is stored in a program library and can be called when needed.

Benefits:

  • Saves development time: Pre-written code means programmers don't need to write everything from scratch
  • Already debugged: Library routines are tested and reliable, reducing errors
  • Reusability: Same routine can be used by multiple programs
  • Consistency: Standard routines ensure consistent behavior
7. Write pseudocode to declare appropriate variables for storing: a person's name, their age, whether they are a student, and their average test score. [4 marks]

Answer:

DECLARE Name : STRING DECLARE Age : INTEGER DECLARE IsStudent : BOOLEAN DECLARE AverageScore : REAL

Marks awarded for:

  • STRING for name (text data) (1 mark)
  • INTEGER for age (whole number) (1 mark)
  • BOOLEAN for student status (true/false) (1 mark)
  • REAL for average score (may have decimals) (1 mark)
8. Explain the difference between the = operator and the ← operator in pseudocode. Give an example of each. [4 marks]

Answer:

= is the equality comparison operator. It compares two values and returns TRUE if they are equal, FALSE otherwise.

is the assignment operator. It assigns a value to a variable.

Examples:

// Assignment Score ← 100 // Sets Score to 100 // Comparison IF Score = 100 THEN OUTPUT "Perfect score!" ENDIF

Additional note: In pseudocode, use = for comparison (not ==) and ← for assignment.

9. Describe the difference between global and local variables. Explain when you might use the global keyword. [5 marks]

Answer:

Global variables are declared outside of functions and can be accessed anywhere in the program.

Local variables are declared inside functions and can only be accessed within that function.

Using the global keyword:

  • Use global when you want to modify a global variable inside a function
  • Without 'global', a new local variable with the same name is created instead
  • This ensures the function accesses the global variable, not creating a new local one
10. A program needs to calculate the final price of an item after applying a discount rate. Write pseudocode that: declares appropriate variables and constants, inputs the original price and discount rate, calculates the discounted price, and outputs the result. [6 marks]

Answer:

CONSTANT Hundred ← 100 DECLARE OriginalPrice : REAL DECLARE DiscountRate : REAL DECLARE DiscountAmount : REAL DECLARE FinalPrice : REAL OUTPUT "Enter the original price:" INPUT OriginalPrice OUTPUT "Enter the discount rate (%):" INPUT DiscountRate DiscountAmount ← OriginalPrice * DiscountRate / Hundred FinalPrice ← OriginalPrice - DiscountAmount OUTPUT "The final price is: ", FinalPrice

Marks awarded for:

  • Appropriate constant declaration (1 mark)
  • Appropriate variable declarations with correct data types (1 mark)
  • INPUT statements for price and rate (1 mark)
  • Correct discount calculation (1 mark)
  • Correct final price calculation (1 mark)
  • OUTPUT statement (1 mark)

10. Glossary

📖 Key Terms
Term Definition
Variable An identifier that can change in the lifetime of a program; a named storage location in memory
Constant An identifier set once in the lifetime of a program; its value cannot be changed during execution
Identifier The name given to a variable or constant; used to refer to a storage location in memory
Declaration The process of creating a variable or constant, specifying its name and data type
Assignment The process of giving a value to a variable using the ← operator
Data Type A classification that specifies what type of value a variable can hold (e.g., INTEGER, STRING)
Pascal Case Naming convention where each word starts with a capital letter with no spaces (e.g., FirstName)
Arithmetic Operator Symbols used to perform mathematical operations (+, -, *, /, ^, MOD)
Logical Operator Symbols used to compare values, returning TRUE or FALSE (=, <>, <, >, <=, >=)
Operator Precedence The rules that determine the order in which operations are evaluated (BODMAS)
MOD Modulus operator; returns the remainder after division of one number by another
Library Routine A debugged block of code designed to handle commonly occurring tasks, stored in a library
Global Variable A variable declared outside a function, accessible from anywhere in the program
Local Variable A variable declared inside a function, accessible only within that function
Scope The region of code where a variable is accessible (global or local scope)
Exponentiation Raising a number to a power; indicated by the ^ operator (e.g., 3^2 = 9)
Concatenation Joining strings together using the + operator (e.g., "Hello" + "World")

11. Exam Success Tips (Part 1)

💡 Variable vs Constant - Quick Check
💡 Declaration Syntax - Remember!

Always include the data type when declaring variables:

DECLARE Name : STRING // NOT: DECLARE Name CONSTANT Pi ← 3.14159 // Constant with value

Common data types: INTEGER, REAL, STRING, BOOLEAN, DATE, CHAR

💡 Operator Confusion - Don't Mix These!
💡 BODMAS - Order Matters!

Always remember the order:

  1. Brackets ( ) - do these first!
  2. Orders (powers ^ )
  3. Division / and Multiplication *
  4. Addition + and Subtraction -

When in doubt, use brackets to make the order clear!

🧠 Memory Trick: BODMAS Rule

Always apply operations in this order:

  1. B - Brackets ( )
  2. O - Orders (powers, ^)
  3. D/M - Division and Multiplication (left to right)
  4. A/S - Addition and Subtraction (left to right)

When in doubt, use brackets to make the order clear!

💡 Data Type Selection
❌ Common Mistakes to Avoid

11. Exam Success Tips (Part 2)

🧠 Memory Trick: MOD = "What's Left"

Think of division in two parts:

Example: 17 ÷ 5 = 3 remainder 2

So: 17 DIV 5 = 3 and 17 MOD 5 = 2

🧠 Memory Trick: Naming Conventions
💡 Writing Complete Programs

When asked to write pseudocode, include ALL parts:

  1. Declarations first: All constants and variables
  2. Input: Get values from user
  3. Processing: Calculations and logic
  4. Output: Display results
⚠️ Pseudocode vs Programming Languages

Remember: Pseudocode has different syntax from Python, Java, or VB.NET:

Feature Pseudocode Python Java
Assignment = =
Equality = == ==
Not equal <> != !=
Declare variable DECLARE x : INTEGER x = 0 int x;
💡 Answer Strategy for Calculation Questions

12. Key Takeaways

📌 Summary Points

Variables & Constants

Operators

Data Types

Library Routines

🌟 Final Tips