Skip to content

Programming

IGCSE Computer Science · Topic 8

Train
8.1

Variables and constants

Syllabus
Candidates should be able to: Notes and guidance
1 Declare and use variables and constants
2 Understand and use basic data types • Including: – integer – real – char – string – Boolean
3 Understand and use input and output
4 (a) Understand and use the concept of sequence
(b) Understand and use the concept of selection • Including: – IF statements – CASE statements
(c) Understand and use the concept of iteration • Including: – count-controlled loops – pre-condition loops – post-condition loops
(d) Understand and use the concepts of totalling and counting
(e) Understand and use the concept of string handling • Including: – length – substring – upper – lower • The first character of the string can be position zero or one
(f) Understand and use arithmetic, relational and logical operators • Arithmetic, limited to: – + – – – / – * – ^ (raised to power of) – MOD – DIV • Relational, limited to: – = – < – <= – > – >= – <> (not equal to) • Logical, limited to: – AND – OR – NOT
5 Understand and use nested statements • Including nested selection and iteration • Candidates will not be required to write more than three levels of nested statements
6 (a) Understand what is meant by procedures, functions and parameters (b) Define and use procedures and functions, with or without parameters (c) Understand and use local and global variables • Procedures and functions may have up to three parameters
7 Understand and use library routines • Including: – MOD – DIV – ROUND – RANDOM
8 Understand how to create a maintainable program • Including appropriate use of: – meaningful identifiers – the commenting feature provided by the programming language – procedures and functions – relevant and appropriate commenting of syntax • Use meaningful identifiers for: – variables – constants – arrays – procedures and functions

Source: Cambridge International syllabus

A variable 变量 is a named store that holds a value which can change while the program runs. A constant 常量 is a named store whose value is fixed and does not change.

A variable named age holding the value 16 A variable is a named store whose value can change

Lines of program code on a screen Variables and constants are named stores for values, set in the program's code

You should declare 声明 them (say their name and type) before use:

DECLARE score : INTEGER
DECLARE name : STRING
CONSTANT Pi = 3.142

Two RAM memory modules While a program runs, its variables are held in the computer's memory (RAM)

Use a constant for a value that never changes (like Pi), so it is set in one place and is easy to read.

Explore

Variables and assignment

Step through the lines and watch each variable take its new value.

Vocabulary Train
English Chinese Pinyin
variable 变量 biàn liàng
constant 常量 cháng liàng
declare 声明 shēng míng
8.1

Data types

A data type 数据类型 says what kind of value a variable holds. You must know five basic types.

Data types: integer (7), real (3.5), char ('A'), string ("hello"), boolean (true/false) The basic data types: integer, real, char, string and boolean

Type Holds Example
integer 整数 a whole number 42, -7
real 实数 a number with a decimal point 3.14, -0.5
char 字符 a single character 'A', '?'
string 字符串 a sequence of characters "Hello"
Boolean 布尔值 one of two values TRUE or FALSE
Vocabulary Train
English Chinese Pinyin
data type 数据类型 shù jù lèi xíng
integer 整数 zhěng shù
real 实数 shí shù
char 字符 zì fú
string 字符串 zì fú chuàn
Boolean 布尔值 bù ěr zhí
8.1

Input and output

Input 输入 reads a value from the user. Output 输出 shows a value on the screen.

OUTPUT "What is your name?"
INPUT name
OUTPUT "Hello ", name
Vocabulary Train
English Chinese Pinyin
input 输入 shū rù
output 输出 shū chū
8.1

The three basic structures

Every program is built from three control structures.

Three small flowcharts: sequence (boxes in a line), selection (a test branching two ways), and iteration (a test with a body that loops back) The three control structures: sequence runs steps in order, selection chooses a branch, iteration repeats a body

Sequence

Sequence 顺序 means the steps run one after another, in order, from top to bottom.

INPUT length
INPUT width
area ← length * width
OUTPUT area

Selection

Selection 选择 chooses which steps to run, based on a condition. Use an IF statement, or a CASE statement when there are many choices.

IF score >= 50 THEN
    OUTPUT "Pass"
ELSE
    OUTPUT "Fail"
ENDIF
CASE OF grade
    'A' : OUTPUT "Excellent"
    'B' : OUTPUT "Good"
    OTHERWISE : OUTPUT "Keep trying"
ENDCASE

Iteration

Iteration 迭代 (a loop 循环) repeats steps. There are three kinds.

A count-controlled loop 计数循环 repeats a fixed number of times:

FOR i ← 1 TO 5
    OUTPUT "Hello"
NEXT i

A pre-condition loop 前测循环 checks the condition before each repeat, so it may run zero times:

WHILE answer <> "stop" DO
    INPUT answer
ENDWHILE

A post-condition loop 后测循环 checks the condition after each repeat, so it always runs at least once:

REPEAT
    INPUT password
UNTIL password = "secret"

Two loop flowcharts: WHILE tests the condition before the body; REPEAT runs the body first and tests after A pre-condition (WHILE) loop tests before the body, so it may run zero times; a post-condition (REPEAT) loop tests after, so it runs at least once

Explore

How an IF … ELSE IF ladder decides

The conditions are tested top to bottom; the FIRST one that is true runs and the rest are skipped. Slide the score and watch which branch lights up.

Explore

Selection

Change the value and watch which branch runs — selection in action.

Vocabulary Train
English Chinese Pinyin
sequence 顺序 shùn xù
selection 选择 xuǎn zé
iteration 迭代 dié dài
loop 循环 xún huán
count-controlled loop 计数循环 jì shù xún huán
pre-condition loop 前测循环 qián cè xún huán
post-condition loop 后测循环 hòu cè xún huán
8.1

Totalling and counting

  • totalling 求和 — keep adding values to a running total: total ← total + value.
  • counting 计数 — add 1 to a counter each time: count ← count + 1.

count = count + 1 counts up by 1; total = total + value adds to a running total A counter counts up by 1; a total builds a running sum

A trace table following a loop over the values 4, 7 and 5: total goes 0, 4, 11, 16 while count goes 0, 1, 2, 3 A trace table follows a totalling and counting loop pass by pass

total ← 0
FOR i ← 1 TO 10
    INPUT mark
    total ← total + mark
NEXT i
OUTPUT total

Worked example. A program must read 5 marks, then output the total and the average.

total ← 0
FOR i ← 1 TO 5
    INPUT mark
    total ← total + mark
NEXT i
average ← total / 5
OUTPUT total, average

Two lines carry the marks. total ← 0 must sit before the loop: put it inside and the total resets on every pass, so the program outputs only the last mark. And average ← total / 5 must sit after the loop, because the total is not complete until every mark has been added. Initialise before, calculate after - that ordering is what the question is really testing.

Vocabulary Train
English Chinese Pinyin
totalling 求和 qiú hé
counting 计数 jì shù
8.1

Operators

Arithmetic operators

Operator Meaning
+ - * / add, subtract, multiply, divide
^ raised to the power of
MOD the remainder 余数 after division
DIV the whole-number part of a division

For example, 17 MOD 5 is 2, and 17 DIV 5 is 3.

Relational operators

These compare two values and give a Boolean result: =, <, <=, >, >=, and <> (not equal to).

Logical operators

These join conditions: AND (both must be true), OR (at least one must be true), NOT (reverses true/false).

Three families of operators: arithmetic operators like plus and times give a number, relational operators like less-than compare and give true or false, logical operators AND OR NOT join conditions The three families of operators: arithmetic, relational and logical

IF age >= 13 AND age <= 19 THEN
    OUTPUT "Teenager"
ENDIF
Vocabulary Train
English Chinese Pinyin
remainder 余数 yú shù
8.1

String handling

A string is made of characters. Useful operations:

  • length 长度 — the number of characters in the string;
  • substring 子串 — a smaller part taken from the string;
  • upper case 大写 — change letters to capitals;
  • lower case 小写 — change letters to small letters.
name ← "Computer"
OUTPUT LENGTH(name)          // 8
OUTPUT SUBSTRING(name, 1, 4) // "Comp"
OUTPUT UCASE(name)           // "COMPUTER"
OUTPUT LCASE(name)           // "computer"

(The first character may be counted as position 0 or position 1, depending on the language.)

Explore

Index and slice a string

Every character has a position (index). A slice takes the characters from the start index up to — but not including — the end index, just like SUBSTRING does.

Vocabulary Train
English Chinese Pinyin
substring 子串 zi chuàn
upper case 大写 dà xiě
lower case 小写 xiǎo xiě
length 长度 cháng dù
8.1

Nested statements

A nested statement 嵌套语句 is one control structure placed inside another. You can nest selection and iteration.

FOR i ← 1 TO 3
    IF i MOD 2 = 0 THEN
        OUTPUT i, " is even"
    ELSE
        OUTPUT i, " is odd"
    ENDIF
NEXT i

You will not have to write more than three levels of nesting.

Vocabulary Train
English Chinese Pinyin
nested statement 嵌套语句 qiàn tào yǔ jù
8.1

Procedures and functions

To avoid repeating code, you can break a program into named blocks.

  • A procedure 过程 is a named block of code that does a task. You run it with CALL.
  • A function 函数 is like a procedure, but it returns a value back to where it was called.

A parameter 参数 is a value passed into a procedure or function (up to three parameters).

PROCEDURE Greet(personName : STRING)
    OUTPUT "Hello ", personName
ENDPROCEDURE

CALL Greet("Sam")
FUNCTION Square(n : INTEGER) RETURNS INTEGER
    RETURN n * n
ENDFUNCTION

answer ← Square(5)   // answer is 25

Local and global variables

  • A local variable 局部变量 is declared inside a procedure or function. It can only be used there.
  • A global variable 全局变量 is declared in the main program. It can be used anywhere.

Local variables are safer, because they cannot be changed by mistake from another part of the program.

Vocabulary Train
English Chinese Pinyin
procedure 过程 guò chéng
function 函数 hán shù
parameter 参数 cān shù
local variable 局部变量 jú bù biàn liàng
global variable 全局变量 quán jú biàn liàng
8.1

Library routines

A library routine 库程序 is a ready-made piece of code you can use. You must know these:

Routine What it does
MOD gives the remainder of a division
DIV gives the whole-number part of a division
ROUND rounds a real number to a number of decimal places
RANDOM gives a random number
Vocabulary Train
English Chinese Pinyin
library routine 库程序 kù chéng xù
8.1

Writing a maintainable program

A maintainable 可维护的 program is easy for other people to read and change later. To make one:

  • use meaningful identifiers 有意义的标识符 — clear names for variables, constants, arrays, procedures and functions (totalScore, not x);
  • add comments 注释 to explain what parts of the code do;
  • use procedures and functions to split the work into small blocks.
Vocabulary Train
English Chinese Pinyin
maintainable 可维护的 kě wéi hù de
meaningful identifiers 有意义的标识符 yǒu yì yì de biāo shí fú
comments 注释 zhù shì
8.2

Arrays

Syllabus
Candidates should be able to: Notes and guidance
1 Declare and use one-dimensional (1D) and two-dimensional (2D) arrays
2 Understand the use of arrays • Including the use of variables as indexes in arrays
3 Write values into, and read values from, an array using iteration • The first index can be zero or one • Including nested iteration

Source: Cambridge International syllabus

An array 数组 is a single variable that holds many values of the same type, found by an index 索引 (a position number).

One-dimensional arrays

A one-dimensional (1D) array 一维数组 is like a single list.

DECLARE scores : ARRAY[1:5] OF INTEGER
scores[1] ← 90
scores[2] ← 75
OUTPUT scores[1]

Five boxes in a row labelled with index 1 to 5, holding values, with the value at index 2 highlighted as 75 A 1D array holds many values in one variable; each is found by its index

You can use a loop to fill or read an array:

FOR i ← 1 TO 5
    INPUT scores[i]
NEXT i

Two-dimensional arrays

A two-dimensional (2D) array 二维数组 is like a table with rows and columns. It uses two indexes.

DECLARE grid : ARRAY[1:3, 1:3] OF INTEGER
grid[1, 1] ← 5
grid[2, 3] ← 8

A 3 by 3 grid with numbered rows and columns; the cell at row 2, column 3 is highlighted and labelled as grid row 2 column 3 A 2D array is a table; each value is found by two indexes, [row, column]

You read a 2D array with a loop inside a loop (nested iteration).

Explore

Arrays

Pick a position to read one element — how a list (array) is indexed.

Vocabulary Train
English Chinese Pinyin
array 数组 shù zǔ
index 索引 suǒ yǐn
one-dimensional (1D) array 一维数组 yī wéi shù zǔ
two-dimensional (2D) array 二维数组 èr wéi shù zǔ
8.3

File handling

Syllabus
Candidates should be able to: Notes and guidance
1 Understand the purpose of storing data in a file to be used by a program
2 Open, close and use a file for reading and writing • Including: – read and write single items of data – read and write a line of text

Source: Cambridge International syllabus

A program can store data in a file 文件 so it is kept after the program stops. You must open the file, use it, then close it.

OPENFILE "data.txt" FOR WRITE
WRITEFILE "data.txt", "Hello"
CLOSEFILE "data.txt"

OPENFILE "data.txt" FOR READ
READFILE "data.txt", line
CLOSEFILE "data.txt"

You can read and write single items of data or a whole line of text. Always close a file when you have finished with it.

Vocabulary Train
English Chinese Pinyin
file 文件 wén jiàn
8.3

Exam tips

  • A variable can change while the program runs; a constant is fixed. Learn the five data types: integer, real, char, string, Boolean.
  • Every program is built from three structures: sequence, selection (IF / CASE), and iteration (loops).
  • A WHILE loop tests before the body, so it may run zero times; a REPEAT … UNTIL loop tests after, so it always runs at least once.
  • MOD gives the remainder and DIV the whole-number part of a division: 17 MOD 5 is 2, 17 DIV 5 is 3.
  • A function returns a value; a procedure does not. A local variable works only inside its block; a global one works anywhere.

Log in or create account

IGCSE & A-Level