Declare and use variables and constants

Programming – Declare and Use Variables and Constants

1. Why Use Variables?

  • Store data that can be read, changed and reused while a program runs.
  • Make programs flexible – no hard‑coding of values.
  • Allow the same algorithm to work with many different inputs.

2. Identifier (Naming) Rules

All languages examined in the Cambridge IGCSE (0478) follow the same basic rules. In the exam identifiers are case‑insensitivetotal and TOTAL are treated as the same name.

RuleDescription
Start with a letter First character must be A‑Z or a‑z.
Allowed characters After the first character you may use letters, digits (0‑9) and the underscore _.
No spaces Use camelCase (e.g. studentScore) or underscores (e.g. student_score) to separate words.
Case‑insensitivity (exam) Upper‑case and lower‑case are considered the same (total = TOTAL).
Reserved words Keywords such as IF, WHILE, INTEGER, DECLARE etc. cannot be used as identifiers.

3. Declaring Variables and Constants

  • Variable declaration – tells the computer the name and the type of data it will hold.
  • Constant declaration – gives a name to a value that must never change.

Cambridge pseudocode syntax

DECLARE age AS INTEGER
DECLARE price AS REAL
DECLARE name AS STRING
CONSTANT MAX_SCORE ← 100
CONSTANT PI ← 3.14159

Note:

  • The assignment operator in exam pseudocode is the left‑arrow . = is never used for assignment.
  • In static languages (Java, C++) the type appears at declaration; in dynamic languages (Python) the type is inferred from the first assigned value.

4. Data Types and Typical Sizes

Data TypeTypical Size (bits)Range / Example Values
INTEGER 16 or 32 ‑215 … 215‑1 (16‑bit) or ‑231 … 231‑1 (32‑bit)
REAL (floating‑point) 32 (single precision) ≈ ±3.4 × 1038 with about 6‑7 decimal digits of precision
CHARACTER 8 Single letters or symbols, e.g. 'A'
STRING Variable Sequences of characters, e.g. "Hello"
BOOLEAN 1 TRUE or FALSE

5. Assignment and Re‑assignment

After a variable has been declared you give it a value with . The value may be changed later.

age ← 15          // first assignment
age ← age + 1     // re‑assignment, now age = 16

6. Input and Output

Cambridge pseudocode uses the keywords INPUT and OUTPUT. The prompt is written in quotation marks.

INPUT "Enter the student's score: ", score
OUTPUT "Result: ", result
OUTPUT "Score = ", score, ", Grade = ", grade

7. Operators

CategoryOperator(s)PurposeExample
Arithmetic +, –, *, /, % Basic maths total ← a + b * c
Relational =, <>, <, ≤, >, ≥ Compare two values IF score ≥ PASS_MARK THEN …
Logical (Boolean) AND, OR, NOT Combine Boolean expressions IF (age ≥ 18) AND (hasID = TRUE) THEN …

8. Selection Structures

  • IF … THEN … ELSE … ENDIF – most common.
  • CASE … OF … ENDCASE – useful when many discrete values are tested.
IF score ≥ PASS_MARK THEN
    result ← "Pass"
ELSE
    result ← "Fail"
ENDIF
CASE grade OF
    "A": OUTPUT "Excellent"
    "B": OUTPUT "Good"
    "C": OUTPUT "Average"
    "D","E","F": OUTPUT "Needs Improvement"
ENDCASE

9. Iteration (Loops)

Repeat a block of code while a condition holds.

  • FOR i ← start TO end STEP step DO … ENDFOR – known number of repetitions.
  • WHILE condition DO … ENDWHILE – repeat while condition is true.
  • REPEAT … UNTIL condition – body executes at least once.
FOR i ← 1 TO 10 STEP 1 DO
    total ← total + i
ENDFOR

10. Arrays (1‑D and 2‑D)

An array stores a collection of values of the same type. The lower and upper bounds must be stated explicitly.

  • 1‑D array declaration: DECLARE marks[1..30] AS INTEGER
  • 2‑D array declaration: DECLARE matrix[1..5,1..5] AS REAL
  • Access with square brackets, e.g. marks[5] ← 78 or matrix[2,3] ← 3.5
FOR i ← 1 TO 30 DO
    INPUT "Enter mark ", i, ": ", marks[i]
ENDFOR

11. File Handling (Basic)

Only the operations required for the syllabus are listed. A complete open‑read‑close cycle is shown.

OPEN "scores.txt" FOR READ
READ "scores.txt", mark1
READ "scores.txt", mark2
// … process data …
CLOSE "scores.txt"
  • OPEN fileName FOR READ – open an existing file for reading.
  • OPEN fileName FOR WRITE – create (or overwrite) a file for writing.
  • READ fileName, variable – read the next value from the file.
  • WRITE fileName, variable – write a value to the file.
  • CLOSE fileName – close the file when finished.

12. Library Routines (Permitted by the Syllabus)

RoutinePurposeExample
ROUND(x) Round a real number to the nearest integer rounded ← ROUND(3.7) // 4
RANDOM() Return a pseudo‑random real number between 0 and 1 r ← RANDOM()
LENGTH(s) Number of characters in a string len ← LENGTH("hello") // 5
LCASE(s), UCASE(s) Convert a string to lower‑case / upper‑case lower ← LCASE("AbC") // "abc"
SUBSTRING(s, start, length) Extract a part of a string sub ← SUBSTRING("Cambridge", 1, 4) // "Cam"
INT(x) Truncate a real number to an integer (discard the fractional part) i ← INT(7.9) // 7

13. Validation & Verification of Input

Before using data, check that it meets the required criteria (validation). After data has been read, additional checks such as a checksum are called verification.

Five common validation checks:

  1. Range check – value lies between a minimum and maximum.
  2. Length check – string has the required number of characters.
  3. Type check – data is of the expected type (INTEGER, STRING, etc.).
  4. Presence check – a value has been entered (not blank).
  5. Format check – value follows a specific pattern (e.g., “DD/MM/YYYY”).
INPUT "Enter age (0‑120): ", age
IF (age < 0) OR (age > 120) THEN
    OUTPUT "Invalid age – please re‑enter."
    // repeat input or abort
ENDIF

Verification example (checksum after reading a file):

READ "data.txt", value, checksum
IF (value MOD 10) ≠ checksum THEN
    OUTPUT "Data corrupted – abort."
ENDIF

14. Trace Tables (Dry‑Run Technique)

A trace table records the values of variables after each step of a program. It helps you verify logic and spot errors before writing code.

Stepagetotaloutput
1 – INPUT15
2 – age ← age + 116
3 – total ← total + age1616
4 – OUTPUT1616"Age is 16, total is 16"

15. Common Mistakes to Avoid

  1. Using a variable before it has been declared or given an initial value.
  2. Changing the value of a constant (constants must remain unchanged).
  3. Confusing identifiers that differ only in case – remember the exam treats them as the same.
  4. Violating naming rules – e.g., starting with a digit, using a reserved word, or omitting the underscore when you intend to separate words.
  5. Writing = instead of for assignment in exam pseudocode.
  6. Omitting required input‑validation checks (range, type, length, presence, format).
  7. Forgetting to state the lower bound when declaring an array (e.g., 1..30).
  8. Leaving out the DO and ENDFOR (or ENDWHILE, ENDREPEAT) keywords in loops.

16. Summary Checklist (Exam‑Ready)

  • Identify the correct data type for each piece of information.
  • Follow the naming conventions; remember identifiers are case‑insensitive.
  • Declare every variable and constant before it is used.
  • Use the left‑arrow for assignment – never use =.
  • Apply the five validation checks (range, length, type, presence, format) before processing input.
  • Choose the appropriate selection structure (IF…THEN…ELSE or CASE…OF) for the problem.
  • Choose the correct iteration structure and write the full keyword sequence (FOR … DO … ENDFOR, etc.).
  • Use arrays when you need to store a collection of similar items; always state the lower and upper bounds.
  • Employ library routines (ROUND, RANDOM, LENGTH, LCASE, UCASE, SUBSTRING, INT) where they simplify calculations.
  • Run a trace table (dry‑run) to verify that variables hold the expected values at each stage.
  • Test the program with several different inputs before the exam.
Suggested diagram: Flow of data – Declaration → Assignment → Validation → Processing → Output (optional re‑assignment).

Create an account or Login to take a Quiz

51 views
0 improvement suggestions

Log in to suggest improvements to this note.