Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

Programming

Igcse programming chapter

Uploaded by

Study Solve Hub
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Programming

Igcse programming chapter

Uploaded by

Study Solve Hub
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

learn how to write programs using pseudocode

• use variables and constants


• learn about the appropriate use of basic data types
• write programs that use input and output
• write programs that use sequence
• write programs that use arithmetic operators
• write programs that use selection including IF and CASE statements
• write programs that include logical and Boolean operators
• write programs that use iteration including count-controlled, pre-condition and post-condition loops
• write programs that use totalling and counting
• write programs that perform the string handling methods length and substring
• write programs that use nested statements
• understand the purpose of subroutines
• understand the differences between procedures and functions
• write programs that use subroutines
• understand the purpose and use of parameters
• write programs with subroutines that take parameters
8 Programming

CONTINUED
• write programs with the library routines MOD, DIV, ROUND and RANDOM
• understand what makes a program maintainable
• add features to programs to improve the maintainability
• understand the use of arrays as data structures
• write programs using 1-dimensional arrays
• write programs using 2-dimensional arrays

understand the need to store data in files


• write programs to read data from a file
• write programs to write data to a file.

GETTING STARTED
Find a computing program (or part of a program) that is written in the
programming language you will be using in-lesson. Work with a friend to
identify what each of the different lines of code do. Present your findings to
the class by showing them each line of code and explaining its purpose.

PROGR AMMING LANGUAGES


There are lots of different procedural programming laolidienn()
languages, for example, Java, VB.NET, Python, 111.dieren Matro

C++ and many, many more. They all have different • �rnq As Lonq 'Ze:ilenanaahl der Tabell�
• arng � !lyte 'SJM,ltenan:r:ahl der Ta!Mlle
commands, requirements for brackets, some • nrnq As Strino 1Naae der Tabelle &lt �reich detin.u:rt

need semi-colons at the end of each line of nq - Cell■ caow:i .Count, 1) ,!nd(xlOp) .Row
ng • Cells fl, COlwana.Count),tnd(xlloLett.),Colw.n
code. There are, however, a set of programming nq • Ac:tiveSheet,N.urie, "•" , "RlCl" ' ":R" ' :r:rnq' "C"' arng
AceiveWorkboOJc. Pi•otCache■. Create (SourceType: •xlConaolid&tio
fundamentals that work in the same way in Array(nrnq, "llen.entl"), Version:•xlPivotTableV
crea"tePivotT•ble TableDe:JJl.ination:•"", Tablell
most (there are always one or two that try to be DefaultVeraion:••l PivotTableVer■ionli
AotiveSbeet. PivotTableWiaard TableDe■tination:•Act
Aotive!lheet.Pivot.Tablas("PivotTable2") . Pivot?ielda(•
different) languages. Once you know what these xlH1dde1'
Act1.veSheet. PivotTable• ("P1.votTable2") , P1votrieldo("5•
fundamentals are, and how these work, then to XlH1dden
With Act1veSheet. PivoeTables ( "P1voeTable2"). Pivot.Fields
.Odentation • :dltovP'ield
program in a new language you just need to check
::1:��:eet,Pivot.Table•("P1votTable2"). RowAn.sLayout xlTabularRov
the syntax which that specific language uses. Active Sheet. Pivot.Table• {"P1votTable2").Repeat.All.LatMl• xlltepeat
ActivaSheet. PivotTabl••("P1VOtTable2"), Pivotrielda("Zeile") ,Subt

• �t�:!::�.!:�::�t��;:� f�;!::�T:�:;�) �:!::�,�:!::•( -!:!1:;.::!·


For example, a FOR loop (a type of count­ , r,1,e false ral••• ruse, ra1aa, ra1aa, raise, Fal••• fal
'1'ctive5he�t. Pu•o�Tablea ("P1Vot?ablel"), P1vot.F1el<U ("Wu:t"l .Su.bt
controlled loop that you will learn about later in , �e1!:��:�t:;!::�1!:!::'c • :�!::�.!;!�!; .
!�!::�i.!�!!��s!:!:��> :�b
ra1ae, r..iaa, ral••• Tal••• f'alae, f'al••• falae. ral.••• Tal.ae,
the chapter) that will output the numbers 1 to 10. On r;rror GoTo Tehler

In pseudocode (a generic non-language specific L------�l'J


x Loh1l
=

language) this could be: w..

FOR Count� 1 TO 10
OUTPUT (Count)
NEXT Count Figure 8.1: Image of a man reading program code

197 )
) CAMBRIDGE IGCSE ™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

CONTINUED
In VB.NET: In Java:

FOR count = 1 to 10 for(count = 1; count < 11; count++) {


Console.writeline(count) System.out.println(count);
NEXT count
These all do the same functions, and they all follow the same principles. They start with the word 'for'. They
have a variable (count). They set the starting value and they say when to stop. So once you can do a for loop
in VB.NET, you should just be able to search for how to do it in Python and just change a couple of the words.

Discussion questions
1 Why do you think all these languages have similar constructs?

2 Find some constructs that are in one language, e.g. VB.NET, and not in another, e.g. Python.

8.1 Programming concepts


This chapter will introduce different code examples. It will show how to do each of the
procedures in three different languages (Java, VB.NET and Python) and pseudocode.
The pseudocode (red font) will always appear as the first code in each example.

Variables and constants


What are variables and constants?
When you are writing a program, you will need to store data; whether this is data that KEYWORDS
has been input, the result of calculations or any for any other reason. You can store
data in variables and constants. variable: a named
memory location
A computer has memory, e.g. RAM. This is made of lots of spaces where you can put
that can store data.
data. Imagine this table is memory. Each of the boxes can store a piece of data.
The data can change
0 10 whilst a program is
running.
1 Red
2 22.5 constant: a named
memory location that
3 True
can store data. The
4 data cannot change
5 whilst a program is
6 running.

7 identifier: a name
given to a variable,
In memory location 0 is the data 10. In memory location 1 is the data red.
constant, data
Each variable and constant is one of these spaces in memory that is given an identifier structure (e.g. array)
(it has a name). In this table the memory numbers have been replaced with their or subroutine.
identifiers. The memory space with the name numberl is storing the piece of data 10.

198 )
8 Programming

numberl 10
colour red
price 22.5
finished True
4
5
6
7

Variables and constants have one difference. In a variable, you can change the data
while the program is running. For example, putting the number 3 0 into memory
location numberl, the memory would then look like this:

numberl 30
colour red
price 22.5
finished True
4
5
6
7

A constant cannot have its value changed while the program is running. When you
declare a constant you put a value into it and this cannot be changed.

KEY WORD
Using variables
Putting data into a variable is done using an assignment statement. The left hand side assignment: a type
of the equals sign is the identifier. The right hand side of the equals sign is the value of programming
(see Figure 8.2). statement that stores
data in a variable or
constant.

number = 10

Figure 8.2: Components of an assignment

Number <-- 10
Colour <-- "red"
Price <-- 22.2

199 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

VB.NET
Dim number As Integer
Dim colour As String
Dim price As Single
number = 10
colour = "red"
price = 22.2

Python
number = 10
colour = "red"
price = 22.2

Java
public static void main(String args[]) {
Integer number = 10;
String colour = "red";
Double price = 22.2;

To get data out of a variable you just use its identifier (see Figure 8.3).

print (number)

Figure 8.3: Printing the contents of a variable

Number r 10
Colour r "red"
OUTPUT(Number)
OUTPUT("The colour is Colour)
Price r Number * 2

VB.NET
Dim number As Integer
Dim colour As String = "red"
Dim price As Single
Console.WriteLine(number)
Console.WriteLine("The colour is " & colour)
price = number * 2

200)
8 Programming

Python
colour = "red"
number = input()
print("The colour is", colour)
price = number * 2

Java
public static void main(String args[]) {
Integer number = 10;
String colour = "red";
System.out.println("The colour is " + colour);
Integer price = number * 2;

Using constants
Before you use a constant in your program you need to give it a value. This is an
assignment statement the same as a variable. (No examples are given for Python as it
does not have in-built constants.)
CONSTANT Colour <-- "yellow"

VB.NET
Const colour As String "yellow"

Java
public static void main(String args[]) {
final String colour = "yellow";

Using the key word constant makes it clear that this value cannot then be changed.
You get data out of a constant the same way as a variable, by using its identifier.
OUTPUT(Colour)

VB.NET
Const colour As String = "yellow"
Console.Writeline(colour)

Java
public static void main(String args[]) {
final String colour = "yellow";
System.out.println(colour);

201 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

8.2 Data types


Data in programs can be of different types. For example, it could be numeric or text.
You will need to tell your program what type of data you want it to store. Some
programming languages need you to declare what type of data your variable will store KEYWORDS
when you first use it. In some programming languages you need to swap data between
types, for example, Python will only output string (text) data, so if you try and output string: a data type.
a number without turning it into a string it will produce an error. Any characters
including letters,
Table 8.1 shows common data types:
numbers and/or
Data type Description Example data symbols.

String Text- characters numbers and "hello" data type: the


symbols. "123" characteristics of
a piece of data.
The data will always need to be inside "help!" Common data types
speech marks, either ' ' or " "
are string, integer,
Integer Whole numbers. 1 real and Boolean.
23 integer: a data type.
-300 Whole numbers.

45656 real: a data type.


Real, single, Decimal numbers. 1. 2 Decimal numbers.
double 23.0 single: a data type.
Decimal numbers.
-20.49
3949.3834 double: a data type.
Decimal numbers.
Boolean Either true or false. TRUE
FALSE Boolean: a data type.
"h" True or False.
Char One character or number of symbol.
II 9 II char: A single
The data will always need to be inside
character, e.g. 'A',
speech marks, either " or "". ti? ..

Table 8.1: Common data types

ACTIVITY 8.1
Take each data type in turn and think of at least 10 different examples of
data that can be stored (apart from Boolean where there can be only two).
From these, identify whether any of these could be more than one data
type, discuss in pairs what options would be valid and which would be most
appropriate.

Peer Assessment
Compare your work with another pair. Identify if all of the data is appropriate
for the data type chosen. Discuss the choices, e.g. if one was more
appropriate than the other?

202)
8 Programming

Storing different data types

Storing a string in a variable:


Colour<- "red"
Storing an integer in a constant:
CONSTANT Value <- 10
Storing a real number in a variable:
Price<- 22.4
Storing a Boolean in a variable:
Flag<- TRUE

VB.NET
Dim colour As String = "red"
Const value As Integer = 10
Dim price As Single 22.4
Dim flag As Boolean = True

Python
colour = "red"
value = 10
price = 22.4
flag = True

Java
public static void main(String args[)) {
String colour = "red";
final Integer value = 10;
Double price 22.4;
Boolean flag = true;

Converting between data types


You might need to turn one data type into another data type. This is not required as KEYWORD
part of the specification, but when you are programming in your chosen language you
might have to do it for your program to work. This is called casting. You can do this by casting: converting
using the name of the data type you want the data to become. data from one data
type to another data
Example 1 type.
Convert a string to an integer:
Number<- int("123")

203 >
> CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

VB.NET
Dim number As Integer
number = Convert.Toint16("123")

Python
number int("123")

Java
public static void main(String args[]) {
Integer number = Integer.parseint("123");

Example 2
Convert a number to a string:
Value � string(22.4)

VB.NET
Dim value As String
value = Convert.ToString(22.4)

Python
value str(22.4)

Java
public static void main(String args[]) {
String value = Double.toString(22.4);

Questions
1 Tick one or more boxes in each row to identify whether each statement refers to
variables and/or constants.
Statement Variable Constant
You cannot change the value when the
program is running.
It has an identifier.
It is a memory location.
You can change its value when the
program is running.
It stores a piece of data.

?04)
8 Programming

2 Write a pseudocode statement to assign the word "house" to a variable named


MyWord.
3 Write a pseudocode statement to declare a constant named MultiplyValue
with the value 10.

8.3 Input and output


Output KEYWORD
A program at some point will probably need to give information to the user. It does
this using output. When outputting strings (characters, letters, etc.). output: data that is
displayed to the user
usually on-screen.
Example 1
Output the words, Hello World:
OUTPUT("Hello world")

VB.NET
Console.WriteLine("Hello World")

Python
print("Hello World!")

Java
public static void main(String args[]) {
System.out.println("Hello World");

Example 2
Output the number 20:
OUTPUT(20)

VB.NET
Console.WriteLine(20)

Python
print(20)

205 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Java
public static void main(String args[]) {
System.out.println(20);

KEY WORD
If you want to output more than one piece of data then you can join them using a
concatenation symbol. Concatenation means join together, so it joins multiple pieces of concatenation:
data together. This could be a comma (, ), an ampersand (&) or a plus (+) depending joining two or more
on your language. All are acceptable in pseudocode. strings together.

Example 1
Output the word Hello, then the contents of variable name:
OUTPUT("Hello ", Name)

VB.NET
Dim name As String = "Alex"
Console.WriteLine("Hello " & Name)

Python
name = "Alex"
print("Hello", name)

Java
public static void main(String args[]) {
String name = "Alex";
System.out.println("Hello " + name);

Example 2
Output the cost of an item stored in the variable cost:
OUTPUT("The cost is " , Cost)

VB.NET
Dim cost As Single = 22.54
Console.WriteLine("The cost is " & cost)

Python
cost = 22.54
print("The cost is", cost)

206)
8 Programming

Java
public static void main(String args[]) {
Double cost= 22.54;
System.out.println("The cost is " +cost);

Example 3
Output the number of balloons stored in the variable balloon:
OUTPUT("There are " , Balloon , " balloons")

VB.NET
Dim balloon As Integer= 100
Console.WriteLine("There are " & balloon & "balloons")

Python
balloon= 100
print("There are", balloon, "balloons")

Java
public static void main(String args[]) {
Integer balloon= 100;
System.out.println("There are "+balloon+" balloons");

In these examples you will see there are spaces within the speech marks. This is because
OUTPUT ("Hello", Name) would join these together, e.g. HelloJane. When writing
in pseudocode it is not important that these are included, but you might need to do it
when outputting in your chosen programming language.

Input KEYWORD
A program might need the user to enter (input) some data. To do this, the command input: the user
word INPUT is used. This cannot appear on its own, otherwise the data entered will entering data into
disappear into space. So you need to do something with it, for example, store it in the program, usually
a variable. from a keyboard.

Example 1
Input a number and store it in a variable:
INPUT Number

VB.NET
Dim number As Integer
number= Console.ReadLine

207 >
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Python
number = int(input())

Java
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
Integer number = Integer.parseint(scanner.nextLine());

Example 2
Tell the user to enter a word and store it in a variable:
OUTPUT("Enter a word")
INPUT Word

VB.NET
Dim word As String
Console.WriteLine("Enter a word")
word = Console.ReadLine

Python
number input("Enter a word")

Java
public static void main(String args[]) {
System.out;println("Enter a word")
Scanner scanner = new Scanner(System.in);
String word = scanner.nextLine();

PROGRAMMING TASK 8.1


A program asks the user to register for a new account. The user needs to enter
key information, e.g. name, date of birth, select a username, etc.

Getting started
1 Work in pairs to list the different items that the program will collect.

2 Identify the most appropriate data type for each of the items you have
identified.

208)
8 Programming

CONTINUED
Practice
1 Select appropriate variables for the items you have identified that you are
going to store.

2 Write a program to ask the user to enter each of the items in turn. Read in
each value and store it in an appropriate variable.

3 Output a message confirming the details that the user has entered.

Challenge
1 The username needs to be at least 8 characters long. Find out how to
work out the length of a string input and output how many characters the
user has entered.

2 Find out how to use selection statements to check the length of the string
and if it is not long enough, ask the user to enter a different username.

KEYWORD

8.4 Arithmetic operators arithmetic


operator: a symbol
Arithmetic operators instruct a program to perform calculations. Table 8.2 describes the
that performs
most common operators, many of which you will know from mathematics. a mathematical
function, e.g. '+'
Operator Description Example
adds two values
+ Adds two values together. 10 + 2 gives 12 together.
11. 3 + 9 gives 20.3
-
Subtracts the second value from the 10 - 2 gives 8
first.
11. 3 - 9 gives 2.3
* Multiplies two values together. 10 * 2 gives 20
11. 3 * 9 gives 101.7
I Divides the first number by the 10 I 2 gives 5
second.
11. 3 I 9 gives 1.256
DIV Gives the whole number after DIV(10, 2) gives 5
the first number is divided by the
DIV(ll, 9) gives 1
second, i.e. it ignores any decimals.
MOD Gives the remainder after the first MOD(10, 2) gives 0
number is divided by the second,
MOD(ll, 9) gives 2
i.e. how many are left.
A
Power of. 2 A
3 = 8
3 A
2 = 9

Table 8.2: Common operators

209)
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

MOD has one special use in programming.It can be used to work out if a number is I
I KEYWORDS
odd or even.If you perform MOD 2 to a number and it returns 0 then it is even, if it
returns 1 then it is odd. MOD: remainder
Example: MOD(l 0, 2) = 0 therefore 10 is even. division. The
remainder after
MOD(l 1, 2)=1 therefore 11 is odd. the division is
performed, e.g.
SKILLS FOCUS 8.1 MOD(5, 2) = 2.

MOD VS DIV DIV: integer division.


The remainder
It is important that you know the difference between MOD and DIV. They are from the division is
similar in their function, but are often confused with division(/). You need to be ignored, e.g. DIV ( 5,
able to use both of these, both to identify the result of the operation, and to be able 2) = 2.
to write programs using them.In this Skills Focus you will be calculating the result
from a MOD and DIV operation.
DIV gives the whole number after the division and ignores any remainder.
a 10/2=v5 There is no remainder, so DIV(l 0, 2)=5.
b 20/7= 2.857 There is a remainder, so DIV(20, 7)= 2(ignore the numbers after
the decimal point).
c 100/21=4.762 There is a remainder, so DIV(l00, 21)=4(ignore the numbers
after the decimal point).
MOD gives the remainder after division. This is not the decimal point, but how
many values are left.
a 10/2=5 There is no remainder, so MOD(l0, 2)=0.
b 20/7= 2.857 There is a remainder. Take the DIV result(2) and multiply it by
the divisor number. 7 * 2= 14. The remainder is how many more numbers are
between 14 and the 20(20- 6). The answer is 6.
c 100/21=4. 76 2 There is a remainder. Take the DIV result(4) and multiply it by
the divisor 21 * 4= 84. The remainder is 100- 84 which is 16.
d 30/9=3.3333 There is a remainder. 9 * 3= 2 7. 30- 2 7=3.
Questions
1 Calculate the result for each of these equations:
a DIV(9, 2) b DIV(! 7, 3)
2 Calculate the result for each of these equations:
a MOD(9, 2) b MOD(1 7, 3)

COMPUTER SCIENCE IN CONTEXT


Many of these arithmetic operators should be familiar to you from
mathematics, where you should be used to working out expressions. In
programming the same principles are used, you write the formulae but not the
answer - the computer works that out because the input data can be changed.

210 )
8 Programming

T he operators for DIV and MOD will differ depending on the programming language
you are usmg.

Example 1
Taking two numbers as input and adding them together:
OUTPUT("Enter the first number")
INPUT Numl
OUTPUT("Enter the second number")
INPUT Num2
Total� Numl + Num2

VB.NET
Dim numl As Integer
Dim num2 As Integer
Dim total As Integer
Console.WriteLine("Enter the first number")
numl = Console.ReadLine
Console.WriteLine("Enter the second number")
num2 = Console.ReadLine
total = numl + num2

Python
numl = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
total = numl + num2

Java
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first number");
Integer numl = Integer.parseint(scanner.nextLine());
System.out.println("Enter the second number");
Integer num2 = Integer.parseint(scanner.nextLine());
Integer total = numl + num2;

Example 2
Subtracting IO from 20:
Numberl � 10
Number2� 20
Result� Number2 - Numberl

VB.NET
Dim numberl As Integer = 10
Dim number2 As Integer = 20
Dim result As Integer
result = number2 - numberl

211 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Python
numberl = 10
number2 = 20
result = number2 - numberl

Java
public static void main(String args[]) {
Integer numberl = 10;
Integer number2 = 20;
Integer result = number2 - numberl;

Example 3
Multiplying two values together:
Numberl +-- 5
OUTPUT("Enter a number")
INPUT Number2
Result +-- Numberl * Number2

VB.NET
Dim numberl As Integer = 5
Dim number2 As Integer
Console.WriteLine("Enter a number")
number2 = Console.ReadLine
Dim result As Integer
result = number2 * numberl

Python
numberl = 5
number2 = int(input("Enter a number"))
result = numberl * number2

Java
public static void main(String args[]) {
Integer numberl = 5;
System.out.println("Enter a number");
Scanner scanner = new Scanner(System.in);
Integer number2 = Integer.parseint(scanner.nextLine());
Integer result = numberl * number2;

212 )
8 Programming

Example 4
Dividing 100 by 5:
Numberl <--- 100
Number2 <--- 5
Result<--- Numberl / Number2

VB.NET
Dim numberl As Integer 100
Dim number2 As Integer 5
Dim result As Single
result = number2 / numberl

Python
numberl = 100
number2 = 5
result = number2 / numberl

Java
public static void main(String args[]) {
Double numberl = 100.0;
Double number2 = 5.0;
Double result = number2 / numberl;

Example 5
Finding the whole number after dividing 33 by 7:
Result<--- DIV(33, 7)

VB.NET
Dim result As Single
result = 33 \ 7

Python
result = int(33 / 7)

Java
public static void main(String args[]) {
Integer result = 33 / 7;

213 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Example 6
Finding the remainder after dividing 33 by 7:
Result� MOD(33, 7)

VB.NET
Dim result As Single
result = 33 Mod 7

Python
result 33 % 7

Java
public static void main(String args[]) {
Integer result = 33 % 7;
KEYWORD
Calculations can use parentheses (brackets) to change the order the calculations are parentheses:
performed in. The calculations within the brackets are done first. brackets in a
mathematical
Example 7 statement. They
determine which
Total� 1 + (2 * 3)
calculations are
Total� (1 + 2) * 3 performed first.
The first line will result in 7 (3 * 2 = 6 + 1 = 7).
The second line will result in 9 (1 + 2 = 3 * 3 = 9).

8.5 Sequence KEYWORD


Sequence is the first of three constructs within programs. A sequence is a series of sequence: a
statements that are executed (run) once, in the order they are written. programming
construct. Instructions
Example 1 are run once and in
the order they are
OUTPUT("Enter a colour")
written.
INPUT Colour
OUTPUT("Enter your name")
INPUT Name
OUTPUT(Name , " your favourite colour is " , Colour)

VB.NET
Dim colour As String
Console.WriteLine("Enter a colour")
colour = Console.ReadLine()
Dim name As String
Console.WriteLine("Enter your name")

214 )
8 Programming

name = Console.ReadLine()
Console.WriteLine(name & " your favourite colour is " & colour)

Python
colour = input("Enter a colour")
name = input("Enter your name")
print(name, "your favourite colour is", colour)

Java
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a colour");
String colour = scanner.nextLine();
System.out.println("Enter your name");
String name = scanner.nextLine();
System.out.println(name + " your favourite colour is " + colour);

This is a sequence. It has 3 lines are executed once, and in the order they are written
(line 1, then 2 then 3).

Example 2
X<- 1
y<- 2
Z <- 3
Total<- X + Y + Z
OUTPUT("Enter the first value")
INPUT Valuel

VB.NET
Dim X As Integer = 1
Dim y As Integer 2
Dim z As Integer 3
Dim total As Integer = X + y + z
Dim valuel As String
Console.WriteLine("Enter the first value")
valuel = Console.ReadLine

Python
X 1
y = 2
z = 3
total = x + y + z
valuel = int(input("Enter the first value"))

215 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Java
public static void main(String args[]) {
Integer X = l;
Integer Y = 2; KEYWORDS
Integer Z = 3;
selection: a
Integer total = X + Y + Z;
programming
String valuel;
construct. A
System.out.println("Enter the first value");
condition is checked
Scanner scanner = new Scanner(System.in);
and this determines
valuel = scanner.nextLine();
which code is run, or
not run.
IF statement: a type
Questions of selection construct
4 Give the result from the following calculations: where the result of
the condition is either
a 10 + 20 e 20 DIV 2 true or false.
b 20 / 2 f 39 DIV 6
CASE statement:
C 100 * 4 g 20 MOD 2 a type of selection
d 50 - 15 h 40 MOD 6 construct where there
is a list of different
5 Write a program to take a number as input, multiply it by 2 and output the result.
values to compare a
6 Write a program to store the numbers 10 and 12 in constants, add them together single value against.
and then output the result.
7 Write a program to ask a user to enter their age and name, then output a message logical operator: a
that uses both values, e.g. Hello Suzie you are 15 year old. symbol that performs
a comparison
resulting in True or

8.6 Selection
False. Can be equals,
not equal to, less
Selection is the second of the three constructs. In selection a condition is checked
than, less than or
equal to, greater
and this determines which, if any, code is run. There are two forms of selection,
IF statements and CASE statements.
than, greater than or
equal to.
Conditions need logical operators. These allow for comparisons to be made. Table 8.3
describes these different operators. Each statement using a logical operator results in
TRUE or FALSE.

Logical operator Description Example


=or== Equals to 10 = 10? would give TRUE. 10 is equal to 10.
10 = 2? would give FALSE. 10 is not equal to 2.
<> or!= Not equal to 10 <> 10? would give FALSE. 10 is not, not equal to 10.
10 <> 2? would give TRUE. 10 is not equal to 2.
< Less than 10 < 11? would give TRUE. 10 is less than 11.
10 < 10? would give FALSE. 10 is not less than 10.
11 < 10? would give FALSE. 11 is not less than 10.
(continued)

216 )
8 Programming

Logical operator Description Example


<= Less than or 10 <= 11? would give TRUE. 10 is less than or equal to 10.
equal to
10 <= 10? would give TRUE. 10 is less than or equal to 10.
11 <= 10? would give FALSE. 11 is not less than or equal to 10.
> Greater than 10 > 11? would give FALSE. 10 is not greater than 11.
10 > 10? would give FALSE. 10 is not greater than 10.
11 > 10? would give TRUE. 11 is greater than 10.
>= Greater than or 10 >= 11? would give FALSE. 10 is not greater than or equal to 11.
equal to
10 >= 10? would give TRUE. 10 is greater than or equal to 10.
11 >= 10? wou Id give TRUE. 11 is greater than or equal to 10.
Table 8.3: Logical operators

SKILLS FOCUS 8.2

COMPARISON OPERATORS
Comparison operators are used in comparison statements; both selection and
iteration. The operators are very similar and you need to know the difference
to make sure you know, a, how to read the statements to make sure you follow
an algorithm correctly, and b, which to select when you are writing your own
comparison statements.
A common error is when less than and greater than are confused. The shape of
them can help you to work out which is correct.
IF ( 10 < 2) The smaller part of the< is nearest the left, the 10. This is the less
than part. So the statement reads if 10 is less than 2. This would result in False
because 10 is not less than 2.
IF ( 150 > 2 5) The larger part of the > is nearest the left, the 150. This is the
greater than part. So the statement reads if 150 is greater than 25. This would result
in True because 150 is greater than 25.
IF ( 3 3 <= 3 4) The smaller part of the<= is nearest the left, the 33. This is the
less than part. There is also an equals after the less than sign. So the statement reads
if 33 is less than or equal to 34. This would result in True, 33 is less than 34.
IF ( 50 > = 7 0 ) The larger part of the > = is nearest the left, the 50. This is the
greater than part. There is also an equals after the less than sign. So the statement
reads if 50 is greater than or equal to 70. This would result in False, 50 is not greater
than or equal to 70.

217 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

CONTINUED
Questions
1 Put each statement into words:
a IF( 1 < 2)
Look at the left of the symbol. Is it small or large? Write the first number,
followed by the symbol name, then the second number.
b IF(6 > 3)
C IF(999 >= 998)
d IF(34 <= 77)
2 Work out if each statement is True or False.
a IF(66 < 40)
b IF(l00 > 101)
C IF(90 <= 45)
d IF(30 >= 30)

IF statements
The command IF is followed by a condition that is created using the logical operators.
T here are three stages of IF statements; IF, ELSE and ELSEIF.
IF has one comparison and the code inside the IF will only run if that condition is
True. If it is not true, the code in the IF statement will not run.
It follows the structure:
IF comparison THEN
Statements that run if the comparison is true
ENDIF

Example 1
This program will check the value in the variable numl is equal to 10. If it is, it will
output the word True.
Numl <-- 10
IF Numl = 10 THEN
OUTPUT( "True")
ENDIF

VB.NET
Dim numl As Integer = 10
If numl = 10 Then
Console.WriteLine("True")
End If

Python
numl = 10
if numl == 10:
print ("True")

218 )
8 Programming

Java
public static void main(String args[]) {
Integer numl = 10;
if(numl == 10) {
System.out.println("True");

Example 2
This program will check if the value input is greater than the one stored in the variable.
OUTPUT("Enter a number")
INPUT Valueinput
StoredValue � 100
IF Valueinput > StoredValue THEN
OUTPUT("It is more than 100")
ENDIF

VB.NET
Dim valueinput As Integer
Console.WriteLine("Enter a number")
valueinput = Console.ReadLine
Dim storedValue As Integer = 100
If valueinput > storedValue Then
Console.WriteLine("It is more than 100")
End If

Python
valueinput = int(input("Enter a number"))
storedValue = 100
if valueinput > storedValue:
print("It is more than 100")

Java
public static void main(String args[]) {
Integer storedValue = 100;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
Integer valueinput = Integer.parseint(scanner.
nextLine());
if(valueinput > storedValue) {
System.out.println("It is more than 100");

219 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

ELSE
This is added within an IF statement. If the IF statement's condition is false then the
ELSE will run. You can only ever have one ELSE in an IF statement.
ELSE follows the structure:
IF comparison THEN
Statements that run if the comparison is true
ELSE
Statements that run if the comparison is false
ENDIF

Example 1
In this example if the two values are the same it outputs "That's correct". If they
are not the same then the ELSE runs, it will output "Incorrect".
Num r 10
OUTPUT("Enter a number")
INPUT Guess
IF Num = Guess THEN
OUTPUT("That's correct")
ELSE
OUTPUT("Incorrect")
ENDIF

VB.NET
Dim num As Integer = 10
Dim guess As Integer
Console.WriteLine("Enter a number")
guess = Console.ReadLine
If num = guess Then
Console.WriteLine("That's correct")
Else
Console.WriteLine("Incorrect")
End If

Python
num = 10
guess = int(input("Enter a number"))
if num == guess:
print("That's correct")
else:
print("Incorrect")

Java
public static void main(String args[]) {
Integer num = 10;
Integer guess;
Scanner scanner = new Scanner(System.in);

220)
8 Programming

System.out.println("Enter a number");
guess = Integer.parseint(scanner.nextLine());
if(num == guess){
System.out.println("That's correct");
}else{
System.out.println("Incorrect");

Example 2
In this example, it will output the smallest number, or one of the numbers if they are
both the same.
Valuel <- 10
Value2 <- 20
IF Valuel < Value2 THEN
OUTPUT(Valuel)
ELSE
OUTPUT(Value2)
ENDIF

VB.NET
Dim valuel As Integer = 10
Dim value2 As Integer = 20
If valuel < value2 Then
Console.WriteLine(valuel)
Else
Console.WriteLine(value2)
End If

Python
valuel = 10
value2 = 20
if valuel < value2:
print(valuel)
else:
print(value2)

Java
public static void main(String args[]){
Integer valuel = 10;
Integer value2 = 20;
if(valuel < value2){
System.out.println(valuel);
}else{
System.out.println(value2);

221 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

ELSEIF
This allows for a second condition to be used within the same IF statement.
If the first condition is False, then a second condition can be checked.
ELSEIF follows the structure:
IF comparisonl THEN
Statements that run if the comparison is true
ELSEIF comparison2 THEN
Statements that run if comparisonl is false, and comparison2 is true
ENDIF

Example 1
This will output which number is greater, or nothing will output if they are the same.
Numl <- 10
Num2 <- 20
IF Numl < Num2 THEN
OUTPUT(Num2)
ELSEIF Num2 < Numl THEN
OUTPUT(Numl)
ENDIF

VB.NET
Dim numl As Integer = 10
Dim num2 As Integer 20
If numl < num2 Then
Console.WriteLine(num2)
Elseif num2 < numl Then
Console.WriteLine(numl)
End If

Python
numl = 10
num2 = 20
if numl < num2:
print(num2)
elif num2 < numl:
print(numl)

Java
public static void main(String args[]) {
Integer numl = 10;
Integer num2 = 20;
if(numl < num2) {
System.out.println(num2);
}else if(num2 < numl) {
System.out.println(num2);

222 )
8 Programming

You can use multiple ELSEIF statements, and combine them with a single ELSE
statement at the end.
This will follow the structure:
IF comparison] THEN
Statements that run if the comparison is true
ELSEIF comparison2 THEN
Statements that run if comparisonl is false, and comparison2 is true
... . as many ELSEIFs as you need
ELSE
Statements that run if none of the comparisons are true
ENDIF

Example 2
This uses ELSEIF and an ELSE to output the largest number.
IF Numl > Num2 THEN
OUTPUT(Numl)
ELSEIF Num2 > Numl THEN
OUTPUT(Num2)
ELSE
OUTPUT("They are the same")
ENDIF

VB.NET
Dim numl As Integer = 10
Dim num2 As Integer 20
If numl > num2 Then
Console.WriteLine(numl)
Elseif num2 > numl Then
Console.WriteLine(num2)
Else
Console.WriteLine("They are the same")
End If

Python
numl = 10
num2 = 20
if numl > num2:
print(numl)
elif num2 > numl:
print(num2)
else:
print( "They are the same")

Java
public static void main(String args[]) {
Integer numl 10;
Integer num2 = 20;

223 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

if(numl < num2){


System.out.println(num2);
}else if(num2 < numl){
System.out.println(num2);
}else{
System.out.println("They are the same");

Example 3
This uses multiple ELSEIFs.
IF Age < 14 THEN
OUTPUT("You are not old enough")
ELSEIF Age < 16 THEN
OUTPUT("You need an adult present")
ELSEIF

VB.NET
Dim age As Integer
Console.WriteLine("Enter your age")
age = Console.ReadLine
If age < 14 Then
Console.WriteLine("You are not old enough")
Elseif age < 16 Then
Console.WriteLine("You need an adult present")
End If

Python
age = int(input("Enter your age"))
if age < 14:
print("You are not old enough")
elif age < 16:
print("You need an adult present")

SELECT CASE
A SELECT CASE statement allows the program to take one variable or value, and then
have lots of different options depending what it is equal to.
CASE follows the structure:
CASE OF variable
valuel:
Statements that run if CASE valuel is true
value2:
Statements that run if CASE valuel is false, and value2 is true
OTHERWISE
Statements that run if none of the comparisons are true.
ENDCASE

224)
8 Programming

A case can have as many CASE statements as needed, but can only ever have a
maximum of one default (this runs if none of the comparisons are true).

Example 1
Using a SELECT CASE to output a grade for an in-lesson test. (No example is given
for Python as it does not have a CASE construct and no example is given for Java as it
does not support switch statements with comparisons, e.g. < or>.)
Score � INPUT("Enter score")
CASE OF score:
>=80: OUTPUT ("A")
>=70: OUTPUT("B")
>=60: OUTPUT("C")
>=50: OUTPUT("D")
OTHERWISE OUTPUT("U")
ENDCASE

VB.NET
Dim score As Integer
Console.WriteLine("Enter score")
score = Console.ReadLine
Select Case score
Case >= 80
Console.WriteLine("A")
Case >= 70
Console.WriteLine("B")
Case >= 60
Console.WriteLine("C")
Case >= 50
Console.WriteLine("D")
Case Else
Console.WriteLine("U")
End Select

Example 2
Output a message depending on which number is entered. (No example is given for
Python as it does not have a CASE construct.)
OUTPUT("Enter a number, 1 to 5"}
INPUT Choice
CASE OF Choice:
1: OUTPUT("Menu option l")
2: OUTPUT("Menu option 2")
3: OUTPUT("Menu option 3")
4: OUTPUT("Menu option 4")
5: OUTPUT("Menu option 5")
OTHERWISE OUTPUT("Invalid choice")
ENDCASE

225 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

VB.NET
Dim choice As Integer
Console.WriteLine("Enter a number, 1 to 5")
choice = Console.ReadLine
Select Case choice
Case 1
Console.WriteLine("Menu option 1")
Case 2
Console.WriteLine("Menu option 2")
Case 3
Console.WriteLine("Menu option 3")
Case 4
Console.WriteLine("Menu option 4")
Case 5
Console.WriteLine("Menu option 5")
Case Else
Console.WriteLine("Invalid choice")
End Select

Java
public static void main(String args[)){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number, 1 to 5");
Integer choice= Integer.parseint(scanner.nextLine());
switch(choice) {
case 1:
System.out.println("Menu option 1");
break;
case 2:
System.out.println("Menu option 2");
break;
case 3:
System.out.println("Menu option 3");
break;
case 4:
System.out.println("Menu option 4");
break;
case 5:
System.out.println("Menu option 5");
default:
System.out.println("Invalid choice");

ACTIVITY 8.2
What is the difference between IF and CASE statements? Is there a scenario
when one is more appropriate than another? Write one example of each
where that is the most appropriate type to use.

226)
8 Programming

CONTINUED
Peer Assessment
Explain your choices in Activity 8.2 to a partner. Did they come to the same
conclusions as you did? Is there always a correct answer or are the different
points of view all valid?

Boolean Operators KEYWORDS


There are three Boolean operators that you can use to join conditions: the AND Boolean operator:
operator, the NOT operator and the OR operator. These are described in Table 8.4.
a symbol that joins
Boolean Description Example
multiple logical
operator
comparisons, can be
AND' OR or NOT.
AND If both conditions are IF 1 = 1 AND 2 = 2
true, the result is true. AND operator:
This will return TRUE. The left of the AND is returns True when
If one or both true, and the right of the AND is true. both inputs are True.
conditions are false,
IF 1 = 1 AND 1 > 2
the result is false. NOT operator:
This will return FALSE. The left of AND is returns True if the
true, but the right of AND is false. input is False, and
False if it is True.
IF 1 < -2 AND O < -1
OR operator: returns
This will return FALSE. Both comparisons True when one, or
are false, so the result is false. both, inputs are True.
OR If one, or both, IF 1 = 1 OR 2 = 2
conditions are true, the
This will return TRUE. The left of the OR is
result is true.
true, and the right of the OR is true.
If both conditions are
IF 1 = 1 OR 1 > 2
false, the result is false.
This will return TRUE. The left of OR is true,
but the right of OR is false.
IF 1 < -2 OR O < -1
This will return FALSE. Both comparisons
are false, so the result is false.
NOT Reverse the condition. IF NOT (1 = 1)
If the condition is True
it becomes False. The brackets equal to TRUE, 1 equals 1.
The NOT makes it FALSE, so it becomes 1
does not equal 1.
IF NOT (End of File)
This is used with file handing. End of
File will return TRUE if there is no data
left in the file. The NOT turns this to false.
So while not at the end of the file.
Table 8.4: Boolean operators

227 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

ACTIVITY 8.3
Make a list of the use of AND, OR and NOT in real-life situations. For
example, if one of two light switches is pressed then a light turns on. If the
door is locked and you have the key then you can unlock the door.

Peer Assessment
Share your list in groups of 3. Discuss each of the statements and whether
they have been correctly identified as AND, OR or NOT. Select one of each
Boolean operator and share it with the rest of the class.

Example 1
This will output the first message if both test marks are greater than or equal to 90.
If only one mark is greater than or equal to 90 then the second message will output.
OUTPUT("Enter the mark for test 1")
INPUT Markl
OUTPUT("Enter the mark for test 2")
INPUT Mark2
IF Markl >= 90 AND Mark2 >= 90 THEN
OUTPUT("Well done you got top marks on both tests")
ELSEIF Markl >= 90 OR Mark2 >= 90 THEN
OUTPUT("Well done you got top marks on one of the tests")
ELSE
OUTPUT("You didn't quite get top marks on the tests, try again next time")
ENDIF

VB.NET
Dim markl As Integer
Console.WriteLine("Enter the mark for test l")
markl = Console.ReadLine
Dim mark2 As Integer
Console.WriteLine("Enter the mark for test 2")
mark2 = Console.ReadLine
If markl >= 90 And mark2 >= 90 Then
Console.WriteLine("Well done you got top marks on both tests")
Elseif markl >= 90 Or mark2 >= 90 Then
Console.WriteLine("Well done you got top marks on one test")
Else
Console.WriteLine("You didn't quite get top marks ont he tests, try again
next time")
End If

Python
markl = input("Enter the mark for test l")
mark2 = input("Enter the mark for test 2")
if markl >= 90 and mark2 >= 90:
print("Well done you got top marks on both tests")
elif markl >= 90 or mark2 >= 90:
print("Well done you got top marks on one of the tests")

228 )
8 Programming

else:
print("You didn't quite get top marks on the tests, try again next time")

Java
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the mark for test l");
Integer markl = Integer.parseint(scanner.nextLine());
System.out.println("Enter the mark for test 2");
Integer mark2 = Integer.parseint(scanner.nextLine());
if(markl >= 90 && mark2 >= 90) {
System.out.println("Well done you got top marks on both tests");
}else if(markl >= 90 11 mark2 >= 90) {
System.out.println("Well done you got top marks on one of the tests");
}else{
System.out.println("You didn't quite get top marks on the tests, try
again next time");

Example 2
Output the highest number out of three that are input:
OUTPUT("Enter 3 numbers")
INPUT Numberl
INPUT Number2
INPUT Number3
IF Numberl > Number2 AND Numberl > Number3 THEN
OUTPUT(Numberl)
ELSEIF Number2 > Number3 THEN
OUTPUT(Number2)
ELSE
OUTPUT(Number3)
ENDIF

VB.NET
Dim numberl As Integer
Console.WriteLine("enter a number")
numberl = Console.ReadLine()
Dim number2 As Integer
Console.WriteLine("enter a number")
number2 = Console.ReadLine
Dim number3 As Integer
Console.WriteLine("enter a number")
number3 = Console.ReadLine
If numberl > number2 And numberl > number3 Then
Console.WriteLine(numberl)
Elseif number2 > number3 Then
Console.WriteLine(number2)
Else
Console.WriteLine(number3)
End If

229)
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Python
numberl = input("Enter a number")
number2 = input("Enter a number")
number3 = input("Enter a number")
if numberl > number2 and numberl > number3:
print(numberl)
elif number2 > number3:
print(number2)
else:
print(number3)

Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
Integer numberl = Integer.parseint(scanner.nextLine());
System.out.println("Enter a number");
Integer number2 = Integer.parseint(scanner.nextLine());
System.out.println("Enter a number");
Integer number3 = Integer.parseint(scanner.nextLine());
if(numberl > number2 && numberl > number3){
System.out.println(numberl);
}else if(number2 > number3){
System.out.println(number2);
}else{
System.out.println(number3);

PROGRAMMING TASK 8.2


A computer program needs writing to act as a calculator. The program should
take in two values and a symbol (e.g. +, -, *or/). Depending on the symbol
entered, the calculator should perform that calculation. For example, if 3 5 + is
entered, then the result should be 8 (3 + 5 = 8).

Getting started
1 Identify the inputs that the system will require.

2 Identify appropriate variables to store the inputs in.

3 Write a program to ask the user to enter the two numbers and symbol,
and store these in variables.

Practice
1 Discuss in pairs which type of selection statement would be most
appropriate for checking the symbol input.

2 Edit your program to use your chosen selection statement to check the
symbol the user has entered. Depending on the symbol, perform the
required calculation and output the result.

230)
8 Programming

CONTINUED
Challenge
1 Discuss in pairs how the inputs could be repeatedly asked for until a valid
entry is given. For example, keep entering a symbol until one of the valid
ones is entered.
2 Implement your idea for repeatedly asking for the symbol to be input until
a valid one is entered.
3 Include additional mathematical operations, for example, power of, KEY WORDS
modulus division.
iteration: a
programming
construct. Code is
Questions run multiple times -
8 Describe what is meant by selection. either a finite number
9 Identify the two different examples of selection. of times (count­
10 Write a program that takes two numbers as input and outputs the largest.
controlled), until
a condition is true
11 Write a program that outputs a question (e.g. a maths question), takes an answer (post-condition), or
from a user and outputs if they are correct or not. while a condition is
12 Ask the user to input a colour. The program should then output a different true (pre-condition).
message if the user enters the word "yel 1 ow", "green" or "blue".
If neither of these are entered, the program should output a different message. loop: another name
Use a CASE statement. for iteration.
count-controlled
loop: a type of
8. 7 Iteration iteration. Code is run
a finite number of
An iteration or loop is a programming construct where statements are run either a finite times. Usually a for
number of times, until a condition is true or while a condition is true. loop.
There are three types of loop: count-controlled, pre-condition and post-condition. pre-condition loop:
a type of iteration.
Code is run while the
Count-controlled condition is true. The
This type of loop uses a counter to run a set number of times. The most common condition is checked
count-controlled loop is the for loop. This has the structure: before running any
code in the loop,
FOR variable� start value TO endvalue therefore the code
Code that runs repeatedly might never run.
NEXT variable
post-condition loop:
The loop will run from the start value to the end value, increasing by 1 each time. If the
a type of iteration.
start value is 1 and the end value is 10, it will run 10 times (1, 2, 3, 4, 5, 6, 7, 8, 9 and 10).
Code is run until a
condition is true. The
Example 1 condition is checked
Output the numbers 1 to 10: after the code in the
loop is run, therefore
FOR X � 1 TO 10
the code always runs
OUTPUT(X)
once.
NEXT X

231 )
> CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

VB.NET
For x = 1 To 10
Console.WriteLine(x)
Next

Python
for x in range(l, 11):
print(x)

Java
public static void main(String args[]) {
for(Integer x = l; x <= 10; x++) {
System.out.println(x);

Example 2
Output the 12 times table from 1 to 12:
FOR Count� 1 TO 12
OUTPUT(Count * 12)
NEXT Count

VB.NET
For count = 1 To 12
Console.WriteLine(count * 12)
Next

Python
for count in range (1, 13):
print(count * 12)

Java
public static void main(String args[]) {
for(Integer count = l; count < 13; count++) {
System.out.println(count * 12);

232 >
8 Programming

Example 3
Add together the first 100 numbers:
Total 0
f-

FOR Number 1 TO 100


f-

Total Total + Number


f-

NEXT Number

VB.NET
Dim total As Integer = 0
For number = 1 To 100
total = total + number
Next

Python
total = 0
for number in range(l, 101):
total = total + number

Java
public static void main(String args[]) {
Integer total = O;
for(Integer number = l; number <= 10; number++) {
total = total + number;

You can change the amount that you increase the variable by each time you loop. This is by using STEP. STEP 1 will
increase the counter by 1 each time. STEP -1 will decrease the counter by 1 each time. STEP O. 5 will increase the
counter by 0.5 each time.

Example 1
Output the numbers 10 to 1:
FOR Number 10 TO 1 STEP -1
f-

OUTPUT(Number)
NEXT Number

VB.NET
For number = 10 To 1 Step -1
Console.WriteLine(number)
Next

233 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Python
for number in range (10, 0, -1):
print(str(number))

Java
public static void main(String args[]) {
for(Integer number = 10; number >= l; number--) {
System.out.println(number);

Example 2
Output the numbers from 11 to 20, increasing by 0.5 each time. (No example is given for Python as it does not support
stepping in decimals.)
FOR Value � 11 TO 20 STEP 0.5
OUTPUT(Value)
NEXT Value

VB.NET
For value = 11 To 20 Step 0.5
Console.WriteLine(value)
Next

Java
public static void main(String args[]) {
for(Double value = 11.0; value <= 20.0; value += 0.5) {
System.out.println(value);

Pre-condition
A pre-condition loop tests the condition before starting the loop. This means that if the condition is false, the code
inside the loop will not run. It loops while the condition is true. It stops looping when the condition is false.
A WHILE loop is a pre-condition loop. It has the structure:
WHILE condition DO
Code that will run when the condition is true
ENDWHILE

234)
8 Programming

Example 1
Looping while the user enters "Yes".
InputValue +- "Yes"
WHILE InputValue = "Yes" DO
InputValue +- INPUT("Do you want to continue?")
ENDWHILE

VB.NET
Dim inputValue As String = "Yes"
While inputValue = "Yes"
Console.WriteLine("Do you want to continue?")
inputValue = Console.ReadLine
End While

Python
inputValue = "Yes"
while inputValue == "Yes":
inputValue = input("Do you want to continue?")

Java
public static void main(String args[]) {
String inputValue = "Yes";
Scanner scanner = new Scanner(System.in);
while(inputValue.equals("Yes")) {
System.out.println("Do you want to continue?");
inputValue = scanner.nextLine();

Example 2
Outputting the numbers 1 to 10:
Number +- 1
WHILE Number < 11 DO
OUTPUT(Number)
Number +- Number + 1
ENDWHILE

VB.NET
Dim number As Integer = 1
While number < 11
Console.WriteLine(number)
number = number + 1
End While

235 )
> CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Python
number = 1
while number < 11:
print(str(number))
number = number + 1

Java
public static void main(String args[]) {
Integer number = 1;
while(number < 11) {
System.out.println(number);
number++;

Example 3
Asking the user to enter a number until they guess the stored number correctly:
Number<- 5
Guessed<- FALSE
WHILE Guessed = FALSE DO
OUTPUT("Guess the number")
INPUT Guess
IF Guess = Number THEN
Guessed<- TRUE
ENDIF
ENDWHILE

VB.NET
Dim number As Integer = 5
Dim guessed As Boolean = False
While guessed = False
Console.WriteLine("Guess the number")
number = Console.ReadLine
If guessed = number Then
guessed = True
End If
End While

Python
number = 5
guessed = False
while guessed == False:
guess = int(input("Guess the number"))
if guess == number:
guessed = True

236 >
8 Programming

Java
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
Integer number = 5;
Boolean guessed = false;
while(guessed == false) {
System.out.println("Guess the number");
Integer guess = Integer.parseint(scanner.nextLine());
if(guess == number) {
guessed = true;

Post-condition loop
A post-condition loop runs the code inside the loop once, and then checks the
condition at the end of the loop. This means that the code will always run once.
A REPEAT UNTIL loop is a post-condition loop. It has the structure:
REPEAT
Code that runs inside the loop
UNTIL Condi tion
In this case it continues until the Condition becomes True. It loops while the condition
is False.

Example 1
Looping until the user enters Yes. (No example is given for Python as it does not have
an in-built post-condition loop.)
REPEAT
OUTPUT("Do you want to stop?")
INPUT Answer
UNTIL Answer = "Yes"

VB.NET
Dim answer As String
Do
Console.WriteLine("Do you want to stop?")
answer = Console.ReadLine
Loop Until answer = "Yes"

Java
Java has a do while loop, so it loops while the condition is true, not until it is true.
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String answer = "Yes";

237 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

do{
System.out.println("Do you want to stop?");
answer = scanner.nextLine();
}while(!answer.equals("Yes"));

Example 2
Outputting the numbers 1 to 10. (No example is given for Python as it does not have an
in-built post-condition loop.)
Number � 1
REPEAT
OUTPUT(Number)
Number � Number + 1
UNTIL Number > 10

VB.NET
Dim number As Integer = 1
Do
Console.WriteLine(number)
number = number + 1
Loop Until number > 10

Java
public static void main(String args[]){
Integer number = l;
do{
System.out.println(number);
number++;
}while(number <= 10);

Example 3
Asking the user to enter a number until they guess the correct number. (No example is
given for Python as it does not have an in-built post-condition loop.)
NumberToGuess � 15
REPEAT
OUTPUT("Guess the number")
INPUT Guess
UNTIL Guess = NumberToGuess

VB.NET
Dim numberToGuess As Integer = 15
Dim guess As Integer

238)
8 Programming

Do
Console.WriteLine("Guess the number")
guess = Console.ReadLine
Loop Until guess = numberToGuess

Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
Integer numberToGuess = 15;
Integer guess;
do{
System.out.println("Guess the number");
guess = Integer.parseint(scanner.nextLine());
}while(numberToGuess != guess);

PROGRAMMING TASK 8.3


A program needs to ask the user to guess what number the game is 'thinking
of'. The game should store the number for the user to guess. The user should
continually guess until they get the correct answer.

Getting started
1 Work in pairs to identify the inputs, processes and outputs required for
this system.

2 Discuss which construct(s) will be needed: sequence, selection and/or


iteration.

3 In pairs plan the algorithm to perform the required tasks.

Practice
1 Write a program for the algorithm you have designed.

2 Change the program so that the program outputs "lower" if their guess is
too high, and "higher" if their guess is too low.

Challenge
1 Change the program to count how many times the user guesses the
number before they get it correct. Output the total when they guess
correctly.

2 Change the program to allow a user to enter the number for the player to
guess at the start of the program.

239)
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

SKILLS FOCUS 8.3

CONVERTING A FOR LOOP TO A WHILE LOOP


The three different types of loop (count-controlled, pre-condition and post­
condition) can often be written as a different type of loop. For example, a count­
controlled loop can be written using a pre-condition loop, or a post-condition
loop. Pre-condition and post-condition loops can be rewritten as each other. Some
pre- and post-condition loops can be written as a count-controlled - but only if their
comparisons are for a count, e.g. looping IO times.
A computational thinking skill is the ability to take a loop and convert it to other
loops. This demonstrates your understanding of how the different loops work and
the characteristics of each type of loop. Therefore it is good practice to experiment
by converting one loop into a different type.
For example, converting a for loop to a while loop.
Consider the for loop:
FOR X <-- 1 TO 10
OUTPUT(X)
NEXT

Step 1: Declare the variable used as the counter. In this example the variable is
x, the value is 1.
Step 2: Take the last value and put it in the while loop condition. In this
example loop until it is 10, so the condition is while x < 11.
Step 3: Increment the counter in the loop. The counter is x so x needs to have 1
added to it.

X = 1 (Step 1)
WHILE X < 11 DO (Step 2)
OUTPUT(X)
X <-- X + 1 (Step 3)
ENDWHILE
Questions
1 Convert the following FOR loop to a WHILE loop.
FOR Count <-- 0 TO 100
OUTPUT(Count + Count)
NEXT

Step 1: Declare your variable with its starting value.


Step 2: Take the last value and put it in the while condition.
Step 3: Increment the counter in the loop.

2 Convert the following FOR loop to a WHILE loop.


FOR New <-- 100 TO 111
OUTPUT(New ANew)
NEXT

240)
8 Programming

Questions
13 Describe the difference between a pre-condition and post-condition loop.
14 A program needs a loop that will run 50 times. Which type of loop would be most
appropriate?
15 Write a program to output the numbers 100 to 200.
16 Write a program to output the 5 times table (from 5 times I, to 5 times 12).
17 Write a program to ask the user to enter a number continually, until they enter the
number 10, using a post-condition loop.
18 Write a program to output the word "Hello" until the user enters the word "stop",
using a pre-condition loop.
19 Convert the following count-controlled loop to a pre-condition loop.
FOR Counter <- 1 to 10
OUTPUT(Counter * Counter)
NEXT Counter

8.8 Totalling KEYWORD


Totalling is adding together a set of values. To write a program to total you need to: totalling: a type of
• program, it adds up
Initialise the total to 0.
multiple values to
• Add the values together (either individually or within a loop). find the total.

Example 1
Asking the user to enter 10 numbers and totalling them:
Total<- 0
FOR Counter<- 0 TO 10
OUTPUT("Enter a number")
Total<- Total + INPUT
NEXT Counter
OUTPUT("The total is " & Total)

VB.NET
Dim total As Integer = 0
For counter = 0 To 10
Console.WriteLine("Enter a number")
total = total + Console.ReadLine
Next
Console.WriteLine("The total is " & total)

Python
total = 0
for counter in range(0, 11):
total = total + int(input("Enter a number"))
print("The total is", total)

241 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Java
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
Integer total = 0;
for(Integer counter = 0; counter < 11; counter++) {
System.out.println("Enter a number");
total = total + Integer.parseint(scanner.nextLine());
}
System.out.println("The total is " + total);

Example 2
Total the data in an array of 100 elements:
Total .- 0
FOR Count<- 0 TO 99
Total .- Total + ArrayData[Count]
NEXT Count
OUTPUT(Total)

VB.NET
Dim total As Integer = 0
Dim arrayData(99) As Integer
'insert code to populate array
For count = 0 To 99
total = total + arrayData(count)
Next
Console.WriteLine(total)

Python
total = 0
arrayData= []
#insert code to populate array
for count in range(0, 100):
total = total + arrayData[count]
print(str(total))

Java
public static void main(String args[]) {
Integer total = 0;
Integer[] arrayData = new Integer[l00];
//insert code to populate array
for(Integer count = 0; count < 100; count++) {
total = total + arrayData[count];

System.out.println(total);

242 )
8 Programming

8.9 Counting KEYWORD


Counting is working out how many of something there are. For example how many counting: a type of
numbers were entered that were over 10. To write a program to count you need to: program, it adds one
• Initialise a counter variable to 0.
for every item to find
out how many there
• Increment (add one to) the counter each time an item is entered, or found . are.

Example 1
Count how many numbers the user enters until they say to stop:
Count <---- 0
Continue <---- "Yes"
WHILE Continue = "Yes" DO
OUTPUT("Do you want to continue?")
INPUT Continue
Count <---- Count + 1
ENDWHILE
OUTPUT("You continued " & Count - 1 & " times")

VB.NET
Dim count As Integer = 0
Dim continueLoop As String Yes 11 11

While continueLoop = "Yes"


Console.WriteLine("Do you want to continue?")
continueLoop = Console.ReadLine
count = count + 1
End While
Console.WriteLine("You continued " & count-1 & " times")

Python
count = 0
continueinput = "Yes"
while continueinput == "Yes":
continueinput = input("Do you want to continue?")
count = count + 1
print("You continued", str(count-1), "times")

Java
public static void main(String args[)) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first number");
Integer count = O;
String continueinput = "Yes";
while(continueinput.equals("Yes")) {
System.out.println("Do you want to continue?");
continueinput = scanner.nextLine();

243)
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

count = count + l;

count = count - 1;
System.out.println("You continued " + count + " times");

Example 2
Count how many numbers in an array of 100 elements are more than 50:
Count <-- 0
FOR X <-- 0 TO 99
IF ArrayData[X] > 50 THEN
Count<-- Count + 1
ENDIF
NEXT X

VB.NET
Dim arrayData(99) As Integer
'insert code to populate array

Dim count As Integer = 0


For X = 0 To 99
If arrayData(X) > 50 Then
count = count + 1
End If
Next

Python
count = 0
arrayData= []
#insert code to populate array
for x in range(0, 100):
if arrayData[x] > 50:
count = count + 1

Java
public static void main(String args[]) {
Integer[] arrayData = new Integer[l00];
//insert code to populate array
Integer count = 0;
for(Integer x = 0; x < 100; x++) {
if(arrayData[x] > 50) {
count = count + 1;

244)
8 Programming

Questions
20 What are the two required elements for a totalling program.
21 What are the two required elements for a counting program.
22 Write a program to ask the user to input 100 numbers, total the values and output
the total.
23 Write a program to ask the user to input numbers. Count how many numbers are
less than 100, and how many are more than or equal to 100. Stop when the user
enters the number 0.

8.10 String manipulation


A string is a piece of text. This could be made up of characters, numbers and/or symbols.
There are lots of different string manipulators that you can use; these let you alter
strings, find values in strings, etc. The two you need to know are length and substring.

Length
This command will return the number of characters in a string. It has the structure:
LENGTH(string)

Example 1
LENGTH( "hi ") would return 2.

VB.NET
Dim stringLength As Integer
stringLength = Len("hi")

Python
stringLength len("Hi")

Java
public static void main(String args[]) {
Integer stringLength = ("hi") .length();

Example 2
LENGTH( "0123") would return 4.

VB.NET
Dim stringLength As Integer
stringLength = Len("0123")

245 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Python
stringLength len("0123")

Java
public static void main(String args[J) {
Integer stringLength = ("0123") .length();

Substring
This command will return some of the characters in the string. It has the structure:
SUBSTRING(string, start character, number of characters).
Depending on your language, the first character could be in position O or position 1.

Example 1
Using substring:
SUBSTRING("Hello", 0, 1) This will start at character 0 and take 1 character.
It will return "H".

VB.NET
(Uses 1 for the first character.)
Dim substring As String
substring = Mid("Hello", 1, 1)

Python
(Uses O for the first character.)
substring = "Hello" (0:1)
print(substring)

Java
public static void main(String args[)) {
String substring = ("Hello") .substring(0,1);
System.out.println(substring);

Example 2
Using substring:
SUBSTRING("Goodbye" , 4 , 3) . This will start at character 4 and take
3 characters. It will return "bye ".

246)
8 Programming

VB.NET
Dim substring As String
substring = Mid("Goodbye", 5, 3)

Python
substring = "Goodbye" [ 4: 7]

Java
public static void main(String args[]) {
String substring = ("Goodbye").substring(S, 3);

Example 3
Output the length of a string that the user inputs:
InputString <-- INPUT("Enter a string")
StringLength <-- LENGTH(InputString)
OUTPUT(InputString & " is " & StringLength & " characters long")

VB.NET
Dim inputString As String
Console.WriteLine("Enter a string")
inputString = Console.ReadLine
Dim stringlength As Integer
stringlength = Len(inputString)
Console.WriteLine(inputString & " is " & stringlength & " characters long")

Python
inputString = input("Enter a string")
stringLength = len(inputString)
print(inputString, " is ", str(stringLength), " characters long")

Java
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string");
String inputString = scanner.nextLine();
Integer stringLength = inputString.length();
System.out.println(inputString + " is " + stringLength + " characters long");

247 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Example 4
Output the first 4 characters in a string:
StringData ..... "Goodbye"
NewMessage f--- SUBSTRING(StringData, 0, 4)
OUTPUT(NewMessage)

VB.NET
Dim stringData As String = "Goodbye"
Dim newMessage As String
newMessage = Mid(stringData, 1, 4)
Console.WriteLine(newMessage)

Python
stringData = "Goodbye"
newMessage = stringData[0:4)
print(newMessage)

Java
public static void main(String args[)) {
String stringData = "Goodbye";
String newMessage = stringData.substring(0,4);
System.out.println(newMessage);

Example 5
Output each letter of a string one character at a time. Depending on your language,
the stopping condition might be the length, or the length -1 depending on
whether the first character is O or 1.
OUTPUT("Enter a message")
INPUT Stringinput
FOR Count f--- 0 to LENGTH(Stringinput) - 1
Character ..... SUBSTRING(Stringinput, Count, 1)
OUTPUT(Character)
NEXT Count

VB.NET
Dim stringinput As String
Console.WriteLine("Enter a message")
stringinput = Console.ReadLine
Dim character As String
For count = 1 To Len(stringinput)
character = Mid(stringinput, count, 1)
Console.WriteLine(character)
Next

248 )
8 Programming

Python
stringinput = input("Enter a message")
for count in range(0, len(stringinput)):
character = stringinput[count:count+l]
print(character)

Java
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a message");
String stringinput = scanner.nextLine();
String character;
for(Integer count = 0; count < stringinput.length(); count++) {
character = stringinput.substring(count, count+l);
System.out.println(character);

Example 6
Output the last 3 characters in a string:
OUTPUT("Enter a message")
INPUT Stringinput
NewString r SUBSTRING(Stringinput, LENGTH(Stringinput) - 3, 3)
OUTPUT(NewString)

VB.NET
Dim stringinput As String
Console.WriteLine("Enter a message")
stringinput = Console.ReadLine
Dim newString As String
newString = Mid(stringinput, Len(stringinput) - 2, 3)
Console.WriteLine(newString)

Python
stringinput = input("Enter a message")
newString = stringinput[len(stringinput)-3:]
print(newString)

Java
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a message");
String stringinput = scanner.nextLine();
String newString = stringinput.substring(stringinput.length()-3, stringinput.
length());
System.out.println(newString);

249 >
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Upper and lower


The characters a z- can be converted into uppercase and the characters A-Z can be
converted into lowercase. This can be done to an individual character, or to an entire
string at the same time. If a character is already in upper case, trying to convert it to
upper case will not change it.
UPPER( string)
LOWER( string)

Example 1
Using UPPER with a string:
UPPER("Hello") will return "HELLO"

VB.NET
Word "Hello".toUpper()

Python
Word "Hello".upper()

Java
Word = "Hello".toUpperCase();

Example 2
Using LOWER with a string stored in a variable:
Word+- "HELLO"
Word+- LOWER(Word)

VB.NET
word = "HELLO"
word = word.toLower()

Python
word = "HELLO"
word = word. lower()

Java
word = "HELLO";
word = word.toLowerCase();

250)
8 Programming

COMPUTER SCIENCE IN CONTEXT


When you need to create a password for a website or computer there are
usually rules you have to follow; e.g. more than 8 characters, at least one
lowercase letter, at least one uppercase letter, one special character, etc. The
length function you have just learnt can be used to work out if the password
is long enough. You can also use the substring function by checking each
character one at a time to work out if it is a special character (e.g./!?, etc.).
You don't need to know about cases for the specification, but you can research
how to find out about a character in upper case , or lowercase as well. Put
them all together and you can write a program to check if a password is valid.

8.11 Nested statements KEY WORD


A nested statement is one or more selection and/or iteration statements inside another nested statement: a
selection/iteration statement. This could be an IF statement inside an IF statement or a construct (selection
loop inside an IF statement or an IF statement in a loop or a loop within a loop. You or iteration) that
might have already used these without realising they were called nested statements. is inside another
construct.
The position of the start and end of these constructs are important. If, for example, a
loop starts inside an IF statement, the loop must also finish inside the same IF statement.

Example 1
Count how many numbers entered are more than 10, and how many are equal to 10:

MoreThanl0 <---- 0
EqualTol0 <---- 0
FOR X <---- 0 TO 99
OUTPUT ( "Enter a number" )
INPUT Number
IF Number > 10 THEN
MoreThanl0 <---- MoreThanl0 + 1
ELSEIF Number = 10 THEN
EqualTol0 <---- EqualTol0 + 1
ENDIF
NEXT X

This code has an IF statement nested inside a count-controlled loop.

VB.NET
Dim moreThanl0 As Integer = 0
Dim equalTol0 As Integer = 0
Dim number As Integer
For x = 0 To 99
Console.WriteLine("Enter a number")
number = Console.ReadLine
If number > 10 Then
moreThanl0 = moreThanl0 + 1
Elseif number = 10 Then

251 >
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

equalTol0 = equalTol0 + 1
End If
Next

Python
moreThanl0 = 0
equalTol0 = 0
for x in range(0, 100):
number = int(input("Enter a number"))
if number > 10:
moreThanl0 = moreThanl0 + 1
elif number = 10:
equalTol0 = equalTol0 + 1

Java
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
Integer moreThanl0 = 0;
Integer equalTol0 = 0;
for(Integer x = 0; x < 100; x++) {
System.out.println("Enter a number");
Integer number = Integer.parseint(scanner.nextLine());
if(number > 10) {
moreThanl0 +=1;
}else if(number == 10) {
equalTol0 +=l;

Example 2
Loop counting how many values in an array are more than or equal to 100, and then
stop counting:
Number � 0
Count� 0
WHILE Number < 10 DO
DatainArray� ArrayData[Count]
Count� Count + 1
IF DatainArray >= 100 THEN
Number� Number + 1
ENDIF
ENDWHILE
This has an IF statement inside a pre-condition loop.

252)
8 Programming

VB.NET
Dim number As Integer = 0
Dim count As Integer = 0
Dim dataArray(999) As Integer
'insert code to populate array

Dim datainArray As Integer


While number < 10
datainArray = dataArray(count)
count = count + 1
If datainArray >= 100 Then
number = number + 1
End If
End While

Python
arrayData = []
#insert code to populate array
number = 0
count = 0
while number < 10:
datainArray = arrayData[count]
count = count + 1
if datainArray >= 100:
number = number + 1

Java
public static void main(String args[]) {
Integer[] dataArray = new Integer[l000];
//insert code to populate array
Integer number = 0;
Integer count = 0;
Integer datainArray = 0;
while(number < 10) {
datainArray = dataArray[count];
count +=l;
if(datainArray >= 100) {
number +=l;

253)
) CAMBRIDGE IGCSE ™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Example 3
Output only the vowels in a message input if user selects option 1:
OUTPUT("Enter 1 or 2")
INPUT Choice
IF Choice = 1 THEN
OUTPUT("Enter a word")
INPUT Word
FOR Count� 0 to LENGTH(Word)-1
Character� SUBSTRING(Word, Count, 1)
IF Character = "a" OR Character = "e" OR Character = "I"
OR Character = "o" OR Character = "u" THEN
OUTPUT(Character)
ENDIF
NEXT Count
ENDIF
This has a FOR loop inside an IF, and another IF inside the FOR loop.

VB.NET
Dim choice As Integer
Console.WriteLine("Enter 1 or 2")
choice = Console.ReadLine
Dim word As String
Dim character As String
If choice = 1 Then
Console.WriteLine("Enter a word")
word = Console.ReadLine
For count = 0 To Len(word)
character = mid(word, count, 1)
If character = "a" Or character = "e" Or character = "i" Or character
"o" Or character = "u" Then
Console.WriteLine(character)
End If
Next
End If

Python
choice = int(input("Enter 1 or 2"))
if choice == 1:
word = input("Enter a word")
for count in range(0, len(word)):
character = word[count:count+l)
if character == "a" or character "e" or character "i" or character
== "o" or character == "u":
print(character)

254)
8 Programming

Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter 1 or 2");
String word;
String character;
Integer choice = Integer.parseint(scanner.nextLine());
if(choice == 1){
System.out.println("Enter a word");
word = scanner.nextLine();
for(Integer count = O; count < word.length(); count++){
character = word.substring(count, count + 1);
if(character.equals("a") 11 character.equals("e") 11 character.
equals("i") 11 character.equals("o") 11 character.equals("u")){
System.out.println(character);

Questions
24 Give one example of a nested statement.
25 What will the pseudocode statement LENGTH ("Hello World!") return?
26 What will the pseudocode statement SUBSTRING("HELLO WORLD! " , 6, 5)
return?
27 Write a program to take a string input from the user, count out how many
numbers are in the string and output the count.
28 Write a program to output a string value backwards. KEYWORDS
subroutine: a self­
contained piece of
8.12 Subroutines code that has an
A subroutine is a self-contained piece of code that has an identifier (name), and it can identifier and can be
be called from anywhere in the main program. called from elsewhere
in a program.
When you decompose a problem into sub-systems, each of the sub-systems can be
written as an individual subroutine. You can then call that subroutine when you need procedure: a
to use it. subroutine that does
not return a value
Subroutines are useful because they reduce code. You write the subroutine once, and to the program that
then you can call it as many times as you need to, instead of having to re-write it every called it.
time. Each time you re-write it there is a chance of an error, so this reduces the chances
of this error. function: a subroutine
that does return a
There are two types of subroutine: procedures and functions. A function returns a value
value to the program
to the program that called it. A procedure does not return a value.
that called it.
Procedures and functions can both take one or more values as parameters. These are
values that are sent to the subroutine. Parameters will be introduced after the basics of parameter: a value
procedures and functions. that is sent to a
subroutine.

255 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Procedures
A procedure runs the code inside it, and does not return a value. The structure of a
procedure is:
PROCEDURE identifier()
code to run inside the function
END PROCEDURE
The identifier is then used in the main program.

Example 1
A procedure to output the numbers 1 to 10:
PROCEDURE OutputlTol0()
FOR Count� 1 to 10
OUTPUT(Count)
NEXT Count
END PROCEDURE
The main program can then call the procedure with the code:
OutputlTol0()

VB.NET
Sub Main()
outputlTol0()
End Sub
Sub outputlTol0()
For count = 1 To 10
Console.WriteLine(count)
Next
End Sub

Python
def outputlTol0():
for count in range(l, 11):
print(str(count))
outputlTol0()

Java
public static void outputlTol0() {
for(Integer count = 0; count < 11; count++) {
Systern.out.println(count);

public static void rnain(String args[]) {


outputlTol0();

256)
8 Programming

Example 2
A procedure to take two numbers from the user and multiply then together:
PROCEDURE Multiply()
OUTPUT ("Enter a number")
INPUT Numl
OUTPUT("Enter a second number")
INPUT Num2
Total� Numl * Num2
ENDPROCEDURE
The procedure can be called in the main program with the code:
multiply()

VB.NET
Sub Main()
multiply()
End Sub
Sub multiply()
Dim numl As Integer
Console.WriteLine("Enter a number")
numl = Console.ReadLine
Dim num2 As Integer
Console.WriteLine("Enter a second number")
num2 = Console.ReadLine
Dim total As Integer
total = numl * num2
End Sub

Python
def multiply() :
numl = int(input("Enter a number"))
num2 = int(input("Enter a second number"))
total = numl * num2
multiply ()

Java
public static void multiply() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
Integer numl = Integer.parseint(scanner.nextLine());
System.out.println("Enter a number");
Integer num2 = Integer.parseint(scanner.nextLine());
Integer total = numl * num2;
}
public static void main(String args[]) {
multiply();

257 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Function
A function returns a value to the program that called it. This can be by either using
the RETURN command, or saving a value to the function's identifier. Once a value is
returned, the function stops running, so it cannot have any code after otherwise this
will not run.
It has the structure:
FUNCTION identifier()
Code to run in the function
RETURN value
ENDFUNCTION
When the function is called it returns a value, so something needs to happen with this
value. It could be output, e.g.
OUTPUT(function identifier)
or it could be saved in a variable, e.g.
variable identifier= function identifier

Example 1
Write a function to ask the user to enter two values, add them together and return
the value:
FUNCTION Multiply()
OUTPUT("Enter a number")
INPUT Numl
OUTPUT( "Enter another number")
INPUT Num2
RETURN Numl * Num2
ENDFUNCTION
To output the return value the main program can use:
OUTPUT(Multiply())

VB.NET
Sub Main()
Console.WriteLine(multiply())
End Sub
Function multiply()
Dim numl As Integer
Console.WriteLine("Enter a number")
numl = Console.ReadLine
Dim num2 As Integer
Console.WriteLine("Enter a second number")
num2 = Console. ReadLine
Return numl * num2
End Function

258 )
8 Programming

Python
def multiply() :
numl = int(input("Enter a number"))
num2 = int(input("Enter another number"))
return numl * num2
print(str(multiply()))

Java
public static Integer multiply() {
Scanner scanner = new Scanner(System.in);
vSystem.out.println("Enter a number");
Integer numl = Integer.parseint(scanner.nextLine());
System.out.println("Enter a second number");
Integer num2 = Integer.parseint(scanner.nextLine());
return(numl * num2);
}
public static void main(String args[]) {
System.out.println(multiply());

Example 2
Write a function to total all the values in an array with 50 elements and then
return the total:
FUNCTION TotalValues()
Total ._ 0
FOR X ._ 0 TO 49
Total ._ Total + Array[X]
NEXT X
RETURN Total
END FUNCTION
To store the return value in a variable in the main program:
Total = TotalValues()

VB.NET
Sub Main()
Dim total As Integer
total = totalValues()
End Sub
Function totalValues()
Dim arrayData(49) As Integer
'insert code to populate array
Dim total As Integer = 0
For x = 0 To 49
total = total + arrayData(x)
Next
Return total
End Function

259 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Python
def totalValues():
arrayData = []
#insert code to populate array
total = 0
for x in range(0, 50):
total = total + arrayData[x]
return total

total = totalValues()

Java
public static Integer totalValues() {
Integer[] arrayData = new Integer[50];
//insert code to populate array
Integer total = 0;
for(Integer x = 0; x < 50; x++){
total = total + arrayData[x];

return total;
}
public static void main(String args[J){
Integer total = totalValues();

Scope KEY WORDS


The scope of a variable is the areas within a program that it can be accessed. scope: the sections in
There are two scopes: global and local. the code where the
variable, or constant,
If you declare a variable (or constant, or array) as global then it means it can be
can be accessed.
accessed by any part of the program. That includes the main program and any
subroutines. In most languages this means declaring it at the top of the program. global scope: the
variable or constant
Example 1 can be accessed
Declaring a global variable, then outputting its value twice. Once in the main program, from any part of the
and once in a procedure call call. program.

GLOBAL Data local scope: the


PROCEDURE OutputData() variable or constant
OUTPUT(Data) can only be accessed
ENDPROCEDURE in the subroutine it is
//main program declared within.
Data� 1
OUTPUT(Data)
OutputData()

260)
8 Programming

VB.NET
Module Program
Dim data As Integer
Sub outputData()
Console.WriteLine(data)
End Sub
Sub Main(args As String())
data = 1
Console.WriteLine(data)
outputData()
End Sub
End Module

Python
data = 1
def outputData():
print(str(data))
print(str(data))
outputData()

Java
class outputting{
static Integer data = l;
public static void outputData(){
System.out.println(data);
}
public static void main(String args[]){
System.out.println(data);
outputData();

If you declare a variable (or constant, or array) as local, then it can only be accessed
in the part of the code where it is declared. If you declare it first in a subroutine,
then it can only be accessed within that subroutine. If you declare it in the main
program, it can only be accessed in the main program.

Example 2
Creating a local variable to the main program and outputting it twice. Once in the main
program, and once from a subroutine where it is sent as a parameter.
PROCEDURE OutputData(DataParameter)
OUTPUT(DataParameter)
ENDPROCEDURE
Data <--- 1
OUTPUT(DataParameter)
OutputData(Data)

261 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

VB.NET
Module Program
Sub outputData(dataParameter)
Console.WriteLine(dataParameter)
End Sub
Sub Main(args As String())
Dim data As Integer
data = 1
Console.WriteLine(data)
outputData(data)
End Sub
End Module

Python
def outputData(dataParameter):
print(str(dataParameter))
#main
data = 1
print(str(data))
outputData(data)

Java
class outputting{
public static void outputData(Integer dataParameter){
System.out.println(dataParameter);

public static void main(String args[]){


Integer data = l;
System.out.println(data);
outputData(data);

Best practice restricts the use of global variables, because their memory is taken for the
whole of the program and nothing else can use that memory space. If you declare them
locally then when that part of the program finishes the memory location is freed. Local
variables are more tricky to program because you need to send them as parameters
between functions and make sure you return them back if they have changed.

Parameters
A parameter is a value that is sent from the main program to the subroutine (procedure
or function). Parameters are declared inside the brackets after the subroutines name, e.g.
PROCEDURE identifier(parameterl, parameter2 ...)
ENDPROCEDURE
or

262 )
8 Programming

FUNCTION identifier(parameterl, parameter2 ...)


ENDFUNCTION
If a subroutine is declared with parameters, then it must be called with the same
number of parameters. For example:
PROCEDURE Total(Numl, Num2)
END PROCEDURE
This has two parameters. When the procedure is called it must have 2 numbers sent to
it. This could be numbers, e.g.
Total(l,2)
or variables. e.g.
Total(Numberl, Number2)

Example 1
A function takes two numbers, divides them and returns the result:
FUNCTION Division(First, Second)
RETURN First/ Second
ENDFUNCTION
The main program sends 10 and 2, then outputs the return value.
OUTPUT(Division(l0, 2))

VB.NET
Sub Main()
Console.WriteLine(division(l0, 2))
End Sub
Function division(first, second)
Return first/ second
End Function

Python
def division(first, second):
return first/ second

print(str(division(l0,2)))

Java
public static Double division(Double first, Double second)
{
return (first/ second);
}
public static void main(String args[J) {
System.out.println(division(l0.0,2.0));

263 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Example 2
A procedure takes 2 values and outputs all the numbers between the first number to
the second:
PROCEDURE OutputNumbers(Numl, Num2)
FOR Count� Numl TO Num2
OUTPUT Count
NEXT Count
ENDPROCEDURE
The main program taking two values from the user.
OUTPUT("Enter the smallest number")
INPUT FirstNumber
OUTPUT("Enter the largest number")
INPUT Second.Number
OutputNumbers(FirstNumber, Second.Number)

VB.NET
Sub Main()
Console.WriteLine("Enter the smallest number")
Dim firstNumber As Integer = Console.ReadLine
Console.WriteLine("Enter the largest number")
Dim second.Number As Integer = Console.ReadLine
outputNumbers(firstNumber, second.Number)
End Sub
Sub outputNumbers(numl, num2)
For count = numl To num2
Console.WriteLine(count)
Next
End Sub

Python
def outputNumbers(numl, num2):
for count in range(numl, num2+1):
print(str(count))

firstNumber = int(input("Enter the smallest number"))


second.Number = int(input("Enter the largest number"))
outputNumbers(firstNumber, second.Number)

Java
public static void outputNumbers(Integer numl, Integer num2) {
for(Integer count = numl; count <= num2; count++) {
System.out.println(count);

264)
8 Programming

public static void main(String args[]) {


Scanner scanner= new Scanner(System.in);
System.out.println("Enter the smallest number");
Integer firstNumber= Integer.parseint(scanner.nextLine());
System.out.println("Enter the largest number");
Integer secondNumber=Integer.parseint(scanner.nextLine());
outputNumbers(firstNumber, secondNumber);

Questions
29 What is the difference between a function and a procedure?
30 Consider the following function:
FUNCTION Calculate(Numl, Num2)
Numl <--- Numl * 2
Num2 <--- Num2 + Numl
RETURN(Numl + Num2)
ENDFUNCTION
What will the following statement output?
OUTPUT(Calculate(l,2))
31 Write a program statement to call the following function with the parameter 100
and output the return value.
FUNCTION FindValue(Number)
Number<--- Number+ INPUT
RETURN Number
ENDFUNCTION
32 Write a procedure to take three numbers as parameters and output the largest.
33 Write a function that takes two strings as parameters. It takes the first 3 characters
of each string and combines them, returning the resulting string.

8.13 Library routines


A program library is a set of subroutines that are pre-written and that can be called
within a program.
In some programming languages the operators for MOD and DIV are library functions.
In other programming languages they are just operators. For example, 2 MOD 4 is the
same as MOD(2, 4). KEYWORD
Two other library routines that you need to know are ROUND and RANDOM. library routine:
a pre-written
subroutine that can
ROUND be called from within
a program.
This will take a real number (decimal) and limit how many numbers there are after the
decimal point.

265 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

For example ROUND(10.123, 1) will take the number 10.123 and only leave 1
number after the decimal point, returning 10.1.
ROUND( 4. 8 293, 2) will return 4. 8 2.
As with functions, the values it returns need to be used. This could be done by
outputting the return value, or saving it in a variable, e.g.
RoundedValue � ROUND(77.293, 1)

VB.NET
Dim roundedValue As Single
roundedValue = Math.Round(77.293, 1)

Python
roundedValue round(77.293,1)

Java
public static void main(String args[]) {
double value = Math.round(77.23 * 10.0) / 10.0;

RANDOM
This will generate a random number between two values that it takes as parameters.
For example, RANDOM(1 O, 2 O) will return a number between 10 and 20.

ACTIVITY 8.4
Is there such a thing as a random number? Research how computers generate
random numbers and work out if there is such a thing as a truly random number.
Find out why randomness is important in programming and what the potential
consequences are of having a system that does not generate random numbers.

RANDOM(1, 4) will return a number between 1 and 4.


As with functions, the values it returns and therefore need to be used. This could be by
outputting the return value, or saving it in a variable, e.g.
randomNumber = RANDOM(l, 100)

VB.NET
Dim randomNumber As Integer
Dim rand As Random = New Random
randomNumber = rand.Next(l, 101)

266)
8 Programming

Python
import random
randomNumber = random.randint(l, 100)

Java
public static void main(String args[]) {
Random rand = new Random();
Integer randomNumber = rand.nextint(l000) + l;

8.14 Maintainable programs KEYWORD


When you write a program there are several things to take into consideration to make it
a maintainable program. This is so that when you come back to it in a week, or a year, maintainable
you can still understand what all of the code does. It might be you are writing a program: a program
program that someone else needs to understand, so you need to make it understandable that has key features
to someone who does not know what the program does. to help it be
understood at a later
date.
Meaningful identifiers
Variables, constants, subroutines and arrays all have identifiers (names). If you call
a variable X, then there is no indication of what it is storing or what its purpose is. If
instead, it is called Total, then you know that it is storing a total.
The identifiers for subroutines are usually descriptions of their function. For example,
a procedure to output the numbers 1 to 10 could be called Functionl, but then there
is no indication of what it does. Instead, it could be called Outpu tl Tol0.

Comments KEYWORD
A comment is a description of a line of code, or section of code. To write a comment comment: text
you use a special character or characters, for example, //. This tells the program not to within a program to
execute the text after this symbol. describe its function,
it is not executed
You do not need to comment every line of code, for example, the statement Count = 0
when the program
does not need commenting, it is clear that it is storing O in the variable count.
1s run.
Example 1
The function of the FOR loop is written as a comment:
FOR Count� 0 TO 9 //Output the first 10 elements in the array
OUTPUT(Array[Count])
NEXT Count

267 >
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

VB.NET
For count = 0 To 9 'output the first 10 elements in the array
Console.WriteLine(arrayData(count))
Next

Python
for count in range(0, 10): output the first 10 elements in the array
print(arrayData[count])

Java
public static void main(String args[]) {
Integer[] arrayData = new Integer[l0];
//insert code to populate the array

//output the first 10 elements in the array


for(Integer count = 0; count < 11; count++) {
System.out.println(arrayData[count])

Example 2
OUTPUT("Enter a number")
INPUT Numl
OUTPUT("Enter a number")
INPUT Num2
//find and output the largest number
IF Numl > Num2 THEN
OUTPUT(Numl)
ELSE
OUTPUT(Num2)
ENDIF

VB.NET
Dim numl As Integer
Dim num2 As Integer
Console.WriteLine("Enter a number")
numl = Console.ReadLine
Console.WriteLine("Enter a number")
num2 = Console.ReadLine

'find and output the largest number


If numl > num2 Then
Console.WriteLine(numl)
Else
Console.WriteLine(num2)
End If

268 )
8 Programming

Python
numl = int( input("Enter a number"))
num2 = int(input("Enter a number"))
# find and output the largest number
if numl > num2:
print(str(numl))
else:
print(str(num2))

Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
Integer numl = Integer.parseint(scanner.nextLine());
System.out.println("Enter a number");
Integer num2 = Integer.parseint(scanner.nextLine());
if(numl > num2) {
System.out.println(numl);
}else{
System.out.println(num2)

Subroutines
Subroutines help to split the code down into sections, especially when one subroutine
may need to be called multiple times. This means that if you need to make any
changes then you only need to make them once. For more on subroutines, look back
at section 8.12.

ACTIVITY 8.5
Open a computer program that you have written . Check its maintainability.
Edit the program to improve the maintainability. Present your before and after
program and explain how you improved its maintainability.

Questions
34 Explain how subroutines help make a program maintainable.
35 Describe two other ways of making a program maintainable.
36 Write a program statement to generate a random number between 1 and 5.
37 Identify the result from the statement ROUND ( 3. 142, 1).

269 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

8.15 Arrays KEYWORDS


An array is a data structure. It allows you store multiple pieces of data in one structure array: a data
with one identifier. In an array, each data item must be of the same data type. If it structure where you
stores integers, then all values must be integers. If it stores strings, then all values must can store multiple
be strings. data items, of the
same data type,
under one identifier.
1-dimensional arrays 1-dimensional array:
A ]-dimensional array has just one row of data. an array that has only
one index.
The best way to visualise an array is with a table:
index: the number
of the space in the
array.

This array has 5 spaces. Each space has an index. In this array the first data item is in
position 0, the data value is 10. In the second array space (index 1), the number 5 is
stored.
Arrays can be 0-indexed or I-indexed. This depends on the programming language that
you use. Some arrays start with Oas the first space. Some arrays start with 1 as the first
space.
Arrays use brackets after the identifier to indicate the index you want to access.
For example, Array [OJ is accessing the first element in the array named Array.
MyData[ 3 J is accessing the fourth element in the array named MyData.

Putting data into an array


You need to know the array identifier and the position where you want to store the
data.

Example 1
Store the colour "red" in the first position of the array named Colour:
Colour[O) � "red"

VB.NET
Dim colour(O) As String
colour(O) = "red"

Python
colour = [" " , " "J
colour[OJ = "red"

270)
8 Programming

Java
public static void main(String args[]) {
String[] colour = new String[l];
colour[□] = "red";

Example 2
Store the colour "yellow" in the second position of the array named Colour:
Colour[l] � "yellow"

VB.NET
Dim colour(l) As String
colour(l) = "yellow"

Python
colour [ 11 11 , " 11 ]
colour[l] = "yellow"

Java
public static void main(String args[]) {
String[] colour = new String[2];
colour[l] = "yellow";

Example 3
Store the number 2 O in the sixth position of the array named Numbers:
Numbers[S] � 20

VB.NET
Dim numbers(9) As String
numbers(S) = 20

Python
numbers = [0,0,0,0,0,0,0,0,0,0]
numbers[S] = 20

Java
public static void main(String args[]) {
Integer[] numbers = new Integer[lO];
numbers[S] = 20;

271 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Getting data out of an array


To access data in an array you need to know the identifier and the position of the data
you want. This will be a value, so you need to do something with this value, e.g. store it
in a variable.

Example 1
Output the first value in the array Colours:
OUTPUT(Colours[0))

VB.NET
Console.WriteLine(Colours(0))

Python
colours = ['red')
print(colours[0))

Java
public static void main(String args[J) {
String[) colours = new String[l0);
System.out.println(colours(0J);

Example 2
Store the second value in the array Colours in a variable:
TheColour � Colours[l)

VB.NET
theColour colours(l)

Python
colours ['red', 'yellow' J
theColour = colours[l)

Java
public static void main(String args[]) {
String(] colours = new String[l0J;
colours[0] = "red";
colours[l) = "yellow";
String theColour = colours[l);

272 )
8 Programming

Example 3
Add 10 to the third value in the array Numbers:
Valuer 10 + Numbers[2]

VB.NET
value = 10 + numbers(2)

Python
numbers = (0,1,2,3,4]
value = 10 + numbers[2]

Java
public static void main(String args[]) {
Integer[] numbers = new Integer[5];
numbers[0] 0;
numbers[l] 1;
numbers[2] = 2.,
numbers[3] = 3;
numbers[4] = 4;
Integer value = 10 + numbers[2];

Using variables as indices


The index in the array might be a variable that stores a number.

Example
Ask the user which array element to output from the array colours:
OUTPUT("Enter the array element you want to output")
INPUT ToOutput
OUTPUT(Colours[ToOutput])

VB.NET
Dim colours(9) As String
colours(0) "red"
colours(l) "yellow"
colours(2) = "black"
colours(3) "green"
Console.WriteLine("Enter the array element you want to output")
Console.WriteLine(colours(Console.ReadLine))

Python
colours = ['red','yellow','black', 'green']
print(colours[int(input("Enter the array element you want to output"))])

273 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Java
public static void main(String args[]) {
String[] colours = new String[l0];
colours[□] "red";
colours[l] "yellow";
colours[2] "black";
colours[3] "green";
System.out.println("Enter the array element you want to output");
Scanner scanner = new Scanner(System.in);
Integer choice = Integer.parseint(scanner.nextLine());
System.out.println(colours[choice]);

Using iteration to read and write


If you have a set of values in an array you can use iteration to loop through each of
the elements in turn. For example, you might want to output all of the values one at a
time. You could add together all of the values in an array and output the total. You
might want to take 10 values in from the user and store each one in the array.
These are all best done using a count-controlled loop. This is because you usually
know how many values you want to enter, or how many values there are in the array
that you want to work through.

Example 1
Output all 10 elements in the array Colours:
FOR Count� 0 TO 9
OUTPUT(Colours[Count])
NEXT Count

VB.NET
Dim colours(9) As String
colours(0) = "red"
colours(l) "yellow"
colours(2) "black"
colours(3) = "green"
colours(4) = "blue"
colours( 5) = "white"
colours(6) "orange"
colours(7) "purple"
colours(8) = "grey"
colours(9) = "maroon"
For count = 0 To 9
Console.WriteLine(colours(count))
Next
8 Programming

Python
colours = ['red','yellow','black', 'green','blue', 'white', 'orange','purple',
'grey','maroon' l
for count in range(0, 10):
print(colours[count])

Java
public static void main(String args[]) {
String[] colours = new String[l0];
colours[0] = "red";
colours[l] = "yellow";
colours[2] "black";
colours[3] "green";
colours[4] "blue";
colours[S] "white";
colours[6] = "orange";
colours[?] = "purple";
colours[B] = "grey";
colours[9] = "maroon";
for(Integer count = 0; count < 10; count++) {
System.out.println(colours[count]);

Example 2
Ask the user to input 20 numbers and store each in the array Numbers:
FOR counter r O TO 19
OUTPUT("Enter a number")
INPUT Numbers[Counter]
NEXT counter

VB.NET
Dim numbers(20) As Integer
For count = 0 To 19
Console.WriteLine("Enter a number")
numbers(count) = Console.ReadLine()
Next

Python
numbers = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0J
for count in range(0, 20):
numbers[count] = int(input("Enter a number"))

275 )
> CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Java
public static void main(String args[)) {
Integer[) numbers = new Integer[20);
Scanner scanner = new Scanner(System.in);
for(Integer count = 0; count < 20; count++) {
System.out.println("Enter a number");
numbers[count) = Integer.parseint(scanner.nextLine());

Example 3
Searching the values in the array values that has 50 values, for the data input by the user:
ValueToFind � INPUT("Enter the value to find")
FOR Count � 0 TO 49
IF Values[Counter) = ValueToFind THEN
OUTPUT("Found it")
ENDIF
NEXT Count

VB.NET
Dim values(49) As Integer
'insert code to populate array
Console.WriteLine("Enter the value to find")
Dim valueToFind As Integer = Console.ReadLine
For count = 0 To 49
Console.WriteLine("Enter a number")
If values(count) = valueToFind Then
Console.WriteLine("Found it")
End If
Next

Python
values = [ J
# insert code to populate array
valueToFind = int(input("Enter the value to find"))
for count in range(0, 50):
if values[counter) = valueToFind:
print("Found it")

Java
public static void main(String args[)) {
Integer[) values= new Integer[50);
//insert code to populate array

Scanner scanner = new Scanner(System.in);


Integer valueToFind = Integer.parseint(scanner.nextLine());

276 >
8 Programming

for(Integer count = O; count < 50; count++) {


System.out.println("Enter a number");
if(values[count] == valueToFind) {
System.out.println("Found it");

2-dimensional arrays KEYWORD

A 2-dimensional array is best viewed as a table with rows and columns. 2-dimensional array:
an array that has two
Index 0 1 2 3 4 indices.
0 10 5 90 26 87
1 3 15 74 62 5
2 7 10 85 4 24
In a 2-dimensional array there are two indices. For example, from the table:
Position[O, OJ is 10.
Position[O, 2] is 7.
Position[4, 2] is 24.

Putting data into an array


You need to know which position, i.e. both indices, the across and the down.

Example 1
Store "red" in the first position in the array Colours:
Colour[O, OJ � "red"

VB.NET
colours(O,O) "red"

Python
numbers = [[''] * 5 for i in range(lO)]
numbers[OJ [OJ = "red"

Java
public static void main(String args[]) {
String[][] colours = new String[lO][10];
colours[OJ [OJ = "red";

277 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Example 2
Store 10 in the array Data, in element 4 across and 3 down:
Data[4, 3] <--- 10

VB.NET
data(4,3) 10

Python
numbers = [[OJ * 5 for i in range(S)]
numbers[4] [3] = 10

Java
public static void main(String args[]) {
Integer[][] data = new Integer[l0J [10];
data[4J [3 J = 10;

Getting data out of an array


You need to know both indices to access the data.

Example 1
Output the data in the array ArrayData, element 5 across and 1 down:
OUTPUT(ArrayData[4, 1])

VB.NET
Console.WriteLine(arrayData(4,1))

Python
arrayData = [[OJ * 5 for i in range(S)J
print(str(arrayData[4][1]))

Java
public static void main(String args[]) {
Integer[][] arrayData = new Integer[S][5];
//insert data to populate array
System.out.println(arrayData[4] [1]);

278 )
8 Programming

Example 2
Access the data in the array colours, in the first element across and the third down:
ColourAccessed� Colours[0, 2]

VB.NET
colourAccessed colours(0,2)

Python
colours = [ [ ' ' ] * 5 for i in range(5)]
colourAccessed = colours[0][2]

Java
public static void main(String args[]) {
String[][] colours = new String[l0][5];
String colourAccessed = colours[0][2];

Using variables as indices


Each index can be stored in a variable in the same way as they can be in a 1 D array.

Example 1
Output the data in element 4, 3:
First� 4
Second� 3
OUTPUT(ArrayData[First, Second])

VB.NET
Dim arrayData(9, 9) As String
'insert code to populate array
Dim first As Integer = 4
Dim second As Integer = 3
Console.WriteLine(arrayData(first, second))

Python
arrayData [ [ ' ' ] * 5 for i in range(5)]
first = 4
second = 3
print(arrayData[first] [second])

279)
> CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Java
public static void main(String args[]) {
String[][] arrayData = new String[l0] [10];
//insert code to populate array
Integer first = 4;
Integer second = 3;
System.out.println(arrayData[first][second]);

Example 2
Ask the user which element to store in data:
OUTPUT("Enter dimension 1")
INPUT Indexl
OUTPUT("Enter dimension 2")
INPUT Index2
Data� Array[Indexl, Index2]

VB.NET
Dim arrayData(9, 9) As String
'insert code to populate array
Dim first As Integer
Console.WriteLine("Enter dimension 1")
first = Console.ReadLine
Dim second As Integer
Console.WriteLine("Enter dimension 2")
second = Console.ReadLine
Dim data As Integer
data = arrayData(indexl, index2)

Python
arrayData = [[''] * 10 for i in range(l0)]
#insert code to populate array

indexl = int(input("Enter dimension 1"))


index2 = int(input("Enter dimension 2"))
data = arrayData[indexl] [index2]

Java
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String[][] arrayData = new String[l0][10];
//insert code to populate array
Integer indexl = Integer.parseint(scanner.nextLine());
Integer index2 = Integer.parseint(scanner.nextLine());
String data = arrayData[indexl][index2];

280)
8 Programming

Using iteration to read and write


Due to the two dimensions, you need two nested loops to read through all the data
elements. If you think about the table again, one loop goes through the columns and
one loop goes through the rows.
The first loop will check row 1. The column will change from 0, 1, 2, 3, 4. The row will
stay the same at 0.

Index 0 1 2 3 4
0 10 5 90 26 87
1 3 15 74 62 5
2 7 10 85 4 24
The first loop will check row 2. The column will change from 0, 1, 2, 3, 4. The row will
stay the same at 1.

Index 0 1 2 3 4
0 10 5 90 26 87
1 3 15 74 62 5
2 7 10 85 4 24
It is best to use count controlled loops to go through the array.
It has the structure:
FOR row� first index to last index
FOR column� first index to last index
Code to run
NEXT row
NEXT count

Example 1
DataArray has 10 elements by 3 elements. Output all of the elements in the array:
FOR Row� 0 TO 2
FOR Column� 0 TO 9
OUTPUT(DataArray[Column, Row])
NEXT Row
NEXT Count

VB.NET
Dim dataArray(2, 9) As Integer
'insert code to populate array

For row = 0 To 2
For column = 0 To 9
Console.WriteLine(dataArray(row, column))
Next
Next

281 >
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Python
arrayData = [[''] * 2 for i in range(l0)]
#insert code to populate array

for row in range(0, 3):


for column in range(0, 10):
print(arrayData[row] [column]

Java
public static void main(String args[]) {
Integer[][] dataArray = new Integer[3][10];
//insert code to populate array
for(Integer row = 0; row < 3; row++) {
for(Integer column = 0; column < 10; column++) {
System.out.println(dataArray[row][column]);

Example 2
Search a 2-dimensional array, with 50 elements by 100 elements, for the value input by
the user:
OUTPUT("Enter a number to search for")
INPUT SearchValue
FOR Row� 0 TO 49
FOR Column� 0 TO 99
IF DataArray[Row, Column] = SearchValue THEN
OUTPUT("Found it at " & Column & " " & Row)
ENDIF
NEXT Column
NEXT Row

VB.NET
Dim dataArray(S0, 100) As Integer
'insert code to populate array
Dim searchValue as Integer
Console.WriteLine("Enter a number to search for")
searchValue = Console.ReadLine()
for (row = 0 to 50)
for(column = 0 to 100)
if(dataArray(row, column) =searchValue) then
Console.WriteLine("Found it at " & column & " " & row)
endif
next
next

282)
8 Programming

Python
arrayData = [[OJ * 50 for i in range(l00))
#insert code to populate array
searchValue = int(input("Enter a number to search for"))
for row in range(0, 50):
for column in range(0, 100):
if arrayData[column)[row) = searchValue:
print("Found it at", str(column), str(row))

Java
public static void main(String args[)) {
Integer[)[) dataArray = new Integer[50) (100);
Scanner scanner = new Scanner(System.in);
Integer searchValue = Integer.parseint(scanner.nextLine());
for(Integer row = 0; row < 50; row++) {
for(Integer column = 0; column < 100; column++) {
if(dataArray[row) [column) == searchValue) {
System.out.println("Found it at " + column + " " + row);

Example 3
Find and output the total of all elements in the each of the first dimensions, in an array
of 10 elements by 15 elements:
FOR Row <- 0 TO 9
Total <- 0
FOR Column <- 0 TO 14
Total <- Total + TheArray[Row, Column)
NEXT Column
OUTPUT("Index " & Row & " has the total " & Total)
NEXT Row

VB.NET
Dim theArray(9, 14) As Integer
'insert code to populate array
Dim total As Integer = 0
For row = 0 To 9
total = 0
For column = 0 To 14
total = total + theArray(row, column)
Next
Console.WriteLine("Index " & row & " has the total " & total)
Next

283 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Python
theArray = [[OJ * 10 for i in range(15)]
#insert code to populate array
total = O
for row in range(O, 10):
for column in range(O, 15):
total = total + theArray[row] [column]
print("Index",row,"has the total",total)

Java
public static void main(String args[]) {
Integer[][] theArray = new Integer[lO] [15];
//insert code to populate array

Integer total = O;
for(Integer row = O; row < 10; row++) {
for(Integer column = O; column < 15; column++) {
total = total + theArray[row][column];

System.out.println("Index " + row + " has the total " + total);

PROGRAMMING TASK 8.4


The 2-player game of noughts and crosses has a grid of 3 squares by
3 squares (Figure 8.4).

Figure 8.4: A noughts and crosses grid

One player is noughts, the other is crosses.

Each player takes it in turn to select a box to place their nought or cross. They
cannot select a box that has already been chosen.

The first player to get three of their symbols in a row (horizontally, vertically or
diagonally) wins. If the board is full and no-one has won then it is a draw.

284)
8 Programming

CONTINUED

Getting started
1 Decompose the problem into its inputs, processes and outputs.
2 Work in pairs to discuss how you will alternate between the players.
3 Work in pairs to discuss how you will check if a player has won.

Practice
1 Write the program to ask each player to make one move. Check that
they have not selected the same box, if they have, ask them to select
another box.
2 Write an algorithm to check if a player has won and either output who has
won, or continue playing.

Challenge
1 Write a function for your algorithm to check if a player has won or not.
This should check all possible ways of winning and return either: X
(crosses has won), 0 (noughts has won) or C (continue play as no-one has
won). Your main program will need to decide whether to end, or continue
based on the value returned.
2 Edit your program to allow the user to play multiple games. The player
should alternate allowing noughts to go first, and then crosses to go first.
3 Edit your program to allow the user to select how many games they
should play. Keep track of how many games each player has won and
output who won overall.

Questions
38 Explain the difference between a variable and an array.
39 Explain why the following code will result in an error.
MyData[O] � 1
MyData[l] � 4
MyData[2] � "7"
MyData[3] � "9"
40 Write a program to read 10 numbers from the user into a 1-dimensional array
named MyNumbers.
41 Write a program to add together all 100 elements in a 1-dimensional array named
MyNumbers.
42 A 2-dimensional array, MyData, has 20 elements by 5 elements. Write a function
that takes a parameter search value. The function should search MyData and
return either TRUE if the parameters is in MyData, or FALSE if the parameters is
not in MyData.

285 )
> CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

8.16 File handling


If you have data in a program, when you stop or close a program all of that data is KEYWORD
lost. If you need to save data to use again later then you need to save it externally into a
text file. The storage and access of data in a file is called file handling. file handling:
programming
statements that
COMPUTER SCIENCE IN CONTEXT
allow text files to be
When playing computer games, for example, on an X-Box or PlayStation, opened, read from,
you are able to save the game and then continue from the same point next written to and closed.
time. It does this by saving data about your current progress in a file. When
your program saves, this data is updated; it might store your current position,
health, points, money, etc. When you restart the program, it goes to this file
and loads the data. This lets you start playing at the exact point you left it.

Reading from a file


You need to be able to read a single item of data, or a single line of text. This means
all of the data will be on the first line in the text file, so you do not need to check
how many lines of text are in the file. Once you have read in the data you can then
manipulate it, for example, if it is a line of text you can split it into individual words, or
use it as one item of data.
To read a value from a file you need to:
• Open the file using its filename (the filename will be a string value).
• Read the data value, and do something with it (e.g. output it, store it in a variable).
• Close the file.
You can use the pseudocode commands:
OPEN filename
variable identifier� READ(filename)
CLOSE filename

Example 1
Reading and outputting a word stored in the text file data.txt:
OPEN "data.txt"
OUTPUT(READ("data.txt"))
CLOSE "data.txt"

VB.NET
Dim theFile As New System.IO.StreamReader("data.txt")
Console.WriteLine(theFile.ReadLine())
theFile.Close()

286)
8 Programming

Python
theFile = open("data.txt", 'r')
print(theFile.read())
theFile.close()

Java
public static void main(String args[]){
try{
FileReader f = new FileReader("data.txt");
BufferedReader reader = new BufferedReader(f);
System.out.println(reader.readLine());
reader.close();
}catch(Exception e) {
System.err.println("No file");

Example 2
Read and output the number stored in the file myNumber.txt by storing the filename
in a variable:
Filename <- "myNumber.txt"
OPEN Filename
TheFileData <- READ(Filename)
CLOSE(Filename)
OUTPUT(TheFileData)

VB.NET
Dim filename As String = "myNumber.txt"
Dim theFileData As String
Dim theFile As New System.IO.StreamReader(filename)
theFileData = theFile.ReadLine()
theFile.Close()
Console.WriteLine(theFileData)

Python
filename = "myNumber.txt"
theFile = open(filename, 'r')
theFileData = theFile.read()
theFile.close()
print(theFileData)

287 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Java
public static void main(String args[]){
String filename = "myNumber.txt";
String theFileData;
try{
FileReader f = new FileReader(filename);
BufferedReader reader = new BufferedReader(f);
theFileData = reader.readLine();
reader.close();
}catch(Exception e){
System.err.println("No file");

Writing to a file
The specification states that you will only need to write a single item of data or a line
of text. This means you will be overwriting any data that is already in the file, you do
not need to worry about appending (to add onto the end) to data that already exists,
or writing multiple values to the same file.
To write a value to a file you need to:
• Open the file using its filename (the filename will be a string value).
• Write the data to the file.
• Close the file.
You can use the pseudocode commands:
OPEN filename
WRITE data
CLOSE filename

Example 1
Write the word "red" to the file colour.txt:
OPEN "colour.txt"
WRITE "red"
CLOSE "colour.txt"

VB.NET
Dim fileWrite As New System.IO.StreamWriter("colour.txt")
fileWrite.WriteLine("red")
fileWrite.Close()

Python
fileData = open("colour.txt", 'w')
fileData.writelines("red")
fileData.close()

288)
8 Programming

Java
public static void main(String args[]){
try{
FileWriter f = new FileWriter("colour.txt");
BufferedWriter out = new BufferedWriter(f);
out.write("red");
out.close();
}catch(Exception e){
System.err.println("No file");

Example 2
Write the number 100 to the file myData.txt storing the filename in a variable:
Filename <- "myData.txt"
OPEN Filename
WRITE 100
CLOSE Filename

VB.NET
Dim filename As String = "myData.txt"
Dim fileWrite As New System.IO.StreamWriter(filename)
fileWrite.WriteLine(l00)
fileWrite.Close()

Python
filename = "myData.txt"
fileData = open(filename, 'w')
fileData.writelines(l00)
fileData.close()

Java
public static void main(String args[J){
try{
String filename = "myData.txt";
FileWriter f = new FileWriter(filename);
BufferedWriter out = new BufferedWriter(f);
out.write(l00);
out.close();
}catch(Exception e){
System.err.println("No file");

289)
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

PROGRAMMING TASK 8.5


A maths quiz game needs to keep a record of the highest number of points
players has gained. The maths quiz is made of randomly generated questions;
the mathematical operation and the numbers are all randomly generated. The
user keeps on being given new questions until they get one wrong. The points
equate to the number of questions they got correct.

Getting started
1 In pairs discuss how the program can randomly generate the numbers
within reasonable bounds, e.g. between 1 and 20.

In pairs discuss how the program can randomly generate the symbol
There are five options
2
limited to+ - /*A_
so a number could
In pairs discuss how the highest score can be stored in a file. Discuss represent each
I
3
when the file will be read from, and when it will be written to. symbol. _J
Practice
1 Write the program to randomly generate one maths question (random
numbers and symbol). Output the question and ask the user for the
answer. Check if it is correct and output an appropriate response.

2 Amend your program to repeatedly ask the user questions until they get
one incorrect. Keep track of how many questions they get correct.

3 Amend your program so when the user gets a question incorrect, the
current high score is loaded from a text file. Replace the high score if the
user has more points.

Challenge
1 Text files can be read one line at a time. Find out how to store more than
one high score (e.g. a top-ten) in a file, and rearrange the high-score table
when a user gains a score worthy of including.

REFLECTION
Consider the program you made for Programming Task 8.5. How did you
decide which stage(s) to complete and when to stop? How did you find
example code that you needed? Was this an efficient method of finding the
required statements?

How did you test your program during development? Did you test the
program after each line of code, or did you write a section? Did this method
work for the program? Would you do it the same way in the future?

How did you test your program once it was complete? Did you set out a
structured test plan with different types of data? Did you ask other people to
help you test it? Was your chosen method appropriate for the program, or did
you have to change it during the testing process?

290)
8 Programming

Questions
43 Why do some programs need to store data in files?
44 What are the three stages that need to be followed to write data to a file?
45 Write a program to read in a value from the file dataStore. txt and output it.
46 Write a program to ask the user to input a filename, then store the word "house"
in the file.

SUMMARY

A variable is a space in memory, with an identifier, that can store a data item that can change while
the program is running.
A constant is a space in memory, with an identifier, that can store a data item that cannot change
while the program is running.
Integer data type stores whole numbers. Real data type stores decimal numbers. Char data type stores
a single character. String data type stores a series of characters. Boolean data type stores True or False.
Input allows the user to enter data into a system.
Output allows the program to display data to the user.
There are three constructs in programming; sequence, selection and iteration.
There are two types of selection; IF and CASE.
IF statements can include ELSEIF and ELSE.
There are three types of iteration; count-controlled loops (a set number of iterations), pre-condition loops
(condition is tested before starting the loop) and post-condition loops (condition is tested after completing
the code in the loop).
Totalling requires initialising the total to 0, then adding the values to it.
Counting requires initialising the count to 0, then adding 1 to it.
Nested statements are when selection/iteration are within a selection/iteration construct.
Subroutines are self-contained code, with an identifier that can be called from elsewhere in the program.
Subroutines reduce repeated code.
Subroutines can be procedures (that do not return a value) or functions (that return a value).
A parameter is a value sent to a subroutine.
Library routines contain pre-written and pre-tested subroutines that can be used in a program.
A maintainable program includes meaningful identifiers, addition of comments and subroutines.
An array allows a set of data, of the same data type, to be stored under one identified.
Each element in an array has an index. This might start at O or 1 depending on your language.

291 )
) CAMBRIDGE IGCSE ™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

CONTINUED

An array can be I-dimensional (one index) or 2-dimensional (two indices).


Iteration can be used to read data to, or from an array, by visiting each index in turn.
Files can be used to store data once a program has finished running.

EXAM-STYLE QUESTIONS
COMMAND WORD
1 Programs can use variables and constants.
a State two similarities between a variable and a constant. [2] state: express in
b State the difference between a variable and a constant. [1l clear terms.

[ Total: 3]
2 Write a program to take two values as input and output first the result
when they are added together, and then the result when they are
multiplied together. [4]
3 The following is a pseudocode algorithm.
INPUT Quantity
Smallest<-- 999
Largest<-- 0
Counter <-- 0
WHILE Counter < Quantity DO
INPUT Value
Total<-- Total + Value
IF (Value > Largest) THEN
Largest<-- Value
ENDIF
IF (Value < Smallest) THEN
Smallest<-- Value
ENDIF
Counter<-- Counter + 1
ENDWHILE
OUTPUT("The average is " & Total/ Quantity)
OUTPUT("The smallest is " & Smallest & " and the
largest is " & Largest) COMMAND WORDS
a Identify the type of iteration used in the algorithm. [1] identify: name /
b State the purpose of the variable counter . [1l select I recognise.
c Give the name of three other variables in the program. [3] give: produce an
d Re-write the loop using a FOR loop. [5] answer from a given
[Total: 10] source or recall /
memory.
4 Write a program to ask the user to enter 20 numbers.
Store each number in an array. [3]

292)
8 Programming

CONTINUED
5 Tick one box in each row to identify whether each if statement would
result in True, False or is an invalid condition.

Statement True False Invalid


if(l0 < 20)
if(l00 > < 2)
if(S >= 5)
if(9 <= 8)
X <- 1
y <- 3
if(x = y)
numl <- 100
num2 <- 200
if(numl and num2)
valuel <- 70
value2 <- 190
if(valuel <> value2)
[7]
6 The 2-dimensional integer array, numbers , has 10 elements by 20 elements.
Write an algorithm to initialise all of the elements to a random integer
value between I and 100. [4]
7 A program stores the x and y coordinates of a character in a game.
The function move () takes an x coordinate as a parameter. It asks
the user to enter a movement (left or right) and changes the coordinate:
• Right increases the coordinate by 1.
• Left decreases the coordinate by 1.
The function then returns the result.
a State why move () is a function and not a procedure. (1]
b The function move loops until the user enters either right or left.
Write the function move () . [7]
[Total: 8]
8 Complete the table by stating how each of the features helps the
maintainability of a program.

Feature How it aids maintainability


Comments
Meaningful identifiers

[2]
9 A procedure twelve () reads an integer number from the text file
number. txt (e.g. 5). It then outputs the 12 times table for that number
(e.g. 5 x 1, 5 x 2 etc.).
Write the procedure twelve () . [6]

293 )
) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

SELF-EVALUATION CHECKLIST
After studying this chapter, think about how confident you are with the different topics.
This will help you to see any gaps in your knowledge and help you to learn more effectively.
You might find it helpful to rate how confident you are for each of these statements when you are revising.
You should revisit any topics that you rated 'Needs more work' or 'Getting there'.

See Needs Getting Confident


I can...
topic more work there to move on
use variables and constants. 8.1
learn about the appropriate use of basic data types. 8.2
write programs that use input and output. 8.3
8.4
write programs that use sequence, selection and iteration 8.5
including nested statements. 8.6
8.7
write programs that use arithmetic, logical and Boolean
8.4
operators.
8.4
write programs that use totalling and counting. 8.8
8.9
write programs that perform the string handling methods. 8.10

write programs that use purpose of procedures and 8.11


functions, including parameters and variable scope. 8.12
write programs using library routines. 8.13
create maintainable programs. 8.14
understand the use of arrays (I-dimensional and
8.15
2-dimensional) as data structures.
write programs to read data from and write data to a file. 8.16

You might also like