Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
2K views

Cambridge IGCSE - O Level Computer Science Programming Book For Microsoft Visual Basic Sample

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
2K views

Cambridge IGCSE - O Level Computer Science Programming Book For Microsoft Visual Basic Sample

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

We are working with Cambridge Assessment International Education towards endorsement of this title.

Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
1  Characteristics & classification of living organisms

LE
P
M
A
S

i
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).

LE
P
M
A
S

Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).

Computer Science

LE
for Cambridge IGCSE™ & O Level
PROGRAMMING BOOK
FOR MICROSOFT® VISUAL BASIC
P Richard Morgan
M
A
S

Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).

University Printing House, Cambridge CB2 8BS, United Kingdom


One Liberty Plaza, 20th Floor, New York, NY 10006, USA
477 Williamstown Road, Port Melbourne, VIC 3207, Australia
314–321, 3rd Floor, Plot 3, Splendor Forum, Jasola District Centre, New Delhi – 110025, India
79 Anson Road, #06–04/06, Singapore 079906

LE
Cambridge University Press is part of the University of Cambridge.
It furthers the University’s mission by disseminating knowledge in the pursuit of education,
learning and research at the highest international levels of excellence.

www.cambridge.org
Information on this title: www.cambridge.org/9781108935678
© Cambridge University Press 2021
This publication is in copyright. Subject to statutory exception and to the provisions of relevant
collective licensing agreements, no reproduction of any part may take place without the written
permission of Cambridge University Press.
First published 2015
Second edition 2021

Printed in Malaysia by Vivar Printing


P
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

A catalogue record for this publication is available from the British Library
ISBN 978-1-108-93567-8 Programming Book Paperback with Digital Access (2 Years)
M
ISBN 978-1-108-94084-9 Digital Programming Book (2 Years)
Additional resources for this publication at www.cambridge.org/go
Cambridge University Press has no responsibility for the persistence or accuracy of URLs for external or third-party internet
websites referred to in this publication, and does not guarantee that any content on such websites is, or will remain, accurate
or appropriate. Information regarding prices, travel timetables, and other factual information given in this work is correct
at the time of first printing but Cambridge University Press does not guarantee the accuracy of such information thereafter.
Exam-style questions and sample answers have been written by the authors. In examinations, the way marks are awarded may be different.
A

References to assessment and/or assessment preparation are the publisher’s interpretation of the syllabus requirements and may not fully
reflect the approach of Cambridge Assessment International Education.
The information in Chapter 12 is based on the Cambridge IGCSE, IGCSE (9–1) and O Level Computer Science syllabuses (0478/0984/2210) for
examination from 2023. You should always refer to the appropriate syllabus document for the year of your examination to confirm the details
and for more information. The syllabus documents are available on the Cambridge International website at www.cambridgeinternational.org
S

NOTICE TO TEACHERS IN THE UK


It is illegal to reproduce any part of this work in material form (including photocopying and electronic storage)
except under the following circumstances:
(i) where you are abiding by a licence granted to your school or institution by the Copyright Licensing Agency;
(ii) where no such licence exists, or where you wish to exceed the terms of a licence, and you have gained the written
permission of Cambridge University Press;
(iii) where you are allowed to reproduce without permission under the provisions of Chapter 3 of the Copyright,
Designs and Patents Act 1988, which covers, for example, the reproduction of short passages within certain types
of educational anthology and reproduction for the purposes of setting examination questions.

Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).

LE
P
M
A
S

Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Contents
The items in orange are available on the digital edition 3.5 Variable scope 42
that accompanies this book. 3.6 Arithmetic operators 43
3.7 More complex arithmetic operators 43
Introduction  vi
3.8 Programming45

LE
How to use this book  viii 3.9 Commenting code 48
How to use this series  x 3.10 Making real-world
scenario-based systems 49
1 Visual Studio Community 3.11 Rounding function 59
1.1 Getting Visual Studio 2019 3.12 Random function 60
Community for Windows 2
4 Selection
1.2 The Integrated Development
Environment3 4.1 The need for selection 64
1.3 Getting started 4 4.2 IF statements 64
1.4 Console application 5 4.3 Single action IF statements 65
1.5
P
Make your first program using
console application 7

Note: Windows Forms application is optional


content. It is not covered in the syllabuses.
4.4
4.5
4.6
4.7
4.8
Logical operators
Coding IF statements in Visual Basic
Multiple decisions
CASE statements
Coding CASE statements in
65
66
68
74
M
1.6 Windows Forms application 10 Visual Basic 75
1.7 Make your first Windows Forms 4.9 Creating complex conditions 82
application13 4.10 Using Boolean operators to
1.8 Choosing a console application or connect criteria 83
Windows Forms application 19 4.11 Connecting more than one value 86
1.9 Additional support 20
5 Iteration
A

2 Programming constructs 5.1 Types of iteration 93


2.1 Programming concepts 22 5.2 FOR loops (count-controlled loops) 93
2.2 Design tools 24 5.3 Using the loop counter 95
2.3 Flowcharts24 5.4 Combining iteration and selection 99
2.4 Pseudocode34 5.5 Common iterative tasks 102
5.6 Condition-controlled loops 107
S

2.5 Use of flowcharts and pseudocode


in programming35 5.7 WHILE loops (pre-condition loops) 107
5.8 WHILE loops with multiple criteria 113
3 Variables and arithmetic operators 5.9 REPEAT...UNTIL loops
3.1 Variables and constants 39 (post-condition loops) 116
3.2 Types of data 39 5.10 WHILE and REPEAT...UNTIL
3.3 Pseudo numbers 40 loops based on user input 119
3.4 Declaring variables and constants 41 5.11 Choosing to use WHILE or UNTIL 123
5.12 Nested iteration 123

vi
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
Contents

6 Designing algorithms 10.3 Initialising arrays 202


6.1 Top-down design 129 10.4 Using arrays 203
6.2 Structure diagrams 129 10.5 Iteration in arrays 208
6.3 Design steps 132 10.6 Grouped data records 212

LE
6.4 The complete design process 138 10.7 Two-dimensional arrays 217
10.8 Sorting224
7 Subroutines and file handling 10.9 Sorting algorithms 225
7.1 Why use subroutines? 141 10.10 Bubble sort 226
7.2 Subroutines in Visual Basic 142
7.3 Functions143
11 Manipulating strings
7.4 Procedures149 11.1 Concatenation235
7.5 File handling 155 11.2 Splitting strings 237
11.3 String index 237
8 Checking inputs 11.4 Substring241
8.1
8.2
8.3

9 Testing
Validation163
Verification164 P
Programming validation into
your systems 165
11.5 Looping through all the characters
in a string244

12 Programming scenario task


12.1
12.2
Getting started on the question 248
M
Planning the program 249
9.1 When to test 186 12.3 Planning your solution  250
9.2 Debugging186 12.4 Writing your program 251
9.3 IDE debugging tools and diagnostics 188 12.5 Checking your program 253
9.4 Identifying logical errors 190 12.6 Final thoughts 254
9.5 Dry running 190
9.6 Breakpoints, variable tracing and
13 Examination practice 258
A

stepping through code 193


9.7 Beta testing 195
Glossary268

10 Arrays Acknowledgements271
10.1 What is an array? 201 Solutions 
10.2 Declaring a one-dimensional array 201
S

vii
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Introduction
I have written this book with two aims in mind. The first is to provide a programming
book that specifically covers the material relevant to the Cambridge IGCSETM,
IGCSE (9–1) and O Level Computer Science syllabuses (0478/0984/2210). The second,
and perhaps more important, aim is to provide you with a start to the exciting and
rewarding process of being able to create your own computer programs.

LE
Language
The syntax and structures used to implement programming techniques will vary across
different languages. The book is entirely based around Visual Basic, one of the three
recommended languages for the syllabuses. Similar books are also available which
focus on the Python and Java programming languages.
Microsoft® Visual Basic offers you, as a programmer, two modes of application.
There is a simple console window in which you can learn and develop programming
skills. It also offers a Windows Forms application, which allows you to program

P
commercial-style applications that offer a graphical user interface through which
users can interact with programs. The language is supported by a fully functional
development environment called Visual Studio Community which is available free
directly from Microsoft. They also provide excellent support and language-specific
tutorials via the Microsoft Developer Network.
M
Support
As you work your way through the exercises in this book you will develop your
computational skills, independent of any specific programming language. You will
do this through the use of program design tools such as structure diagrams and
flowcharts. You will also make use of pseudocode, a structured method for describing
the logic of computer programs.
A

It is crucial that you become familiar with these techniques. Throughout this book all
the programming techniques are demonstrated in the non-language-specific format.
To support learning, all the chapters include examination-style tasks, both within
the chapter and as end-of-chapter tasks. Solutions to all the chapter tasks can be
found on the accompanying digital version of this book. There is also a chapter of
exam-style questions, which has a sample mark scheme prepared by the author, giving
S

possible solutions.

viii
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
Introduction

Developing programming skills


One of the advantages of Visual Basic is that it provides a language that encourages
you to program solutions making use of the basic programming constructs: sequence,
selection and iteration. Although the language does have access to many powerful

LE
prewritten code libraries, they are not generally used in this book.
Computational thinking is the ability to resolve a problem into its constituent parts
and to provide a logical and efficient coded solution. Experience of teaching GCSE
and A level computer science for more than 15 years tells me that knowing how to
think computationally relies much more on an understanding of the underlying
programming concepts than on the ability to learn a few shortcut library routines.
This book is aimed at teaching those underlying skills which can be applied to the
languages of the future.
It is without doubt that programming languages will develop over the coming years but
the ability to think computationally will remain a constant. As technology increasingly

P
impacts on society, people with computation thinking skills will be able to help shape
the way that technology impacts on our future.
M
A
S

ix
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

How to use this book


Throughout this book, you will notice lots of different features that will help your learning. These are explained below.

LEARNING INTENTIONS
These set the scene for each chapter, help with navigation through the Visual Basic programming process and

LE
indicate the important concepts in each topic.

SKILLS FOCUS KEY WORDS


This feature supports your computational thinking, mathematical and programming Key vocabulary
skills. They include useful explanations, step-by-step examples and questions for you is highlighted in
to try out yourselves. the text when it is
first introduced.
Definitions are then
Pseudocode and Code snippets given in the margin,

Dim Number As Integer


Number = Console.ReadLine()
P
This structured method for describing the logic of computer programs may be very
similar to the pseudocode used in the syllabuses.
which explain the
meanings of these
words and phrases.
You will also find
definitions of these
words in the glossary
M
at the back of this
If Number > 0 Then book.
If Number Mod 2 = 0 Then
'accept number'
Else
'reject number' TIP
End If These are short
Else suggestions to
A

'reject number remind you about


End If important learning
Code snippet 4.6: Different coded approaches to the positive even number task points. For example,
a tip to help
Pseudocode is shown in the text like this: clear up
// Entering the values misunderstandings
INPUT Number1 between pseudocode
S

INPUT Number2 and Visual Basic.


// Calculate the addition and store in Answer
Answer  Number1 + Number2
// Output the value in Answer
OUTPUT Answer

Further Information: This feature highlights the advanced aspects in this


book that go beyond the immediate scope of the syllabuses.

x
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
How to use this book

Programming tasks
Programming tasks give you the opportunity to develop your programming and
problem-solving skills. Answers to these questions can be found in the solutions
chapter, on the digital part of this resource. There are three different types of
programming tasks:

LE
DEMO TASKS
You will be presented with a task and a step-by-step solution will be
provided to help familiarise you with the techniques required.

PRACTICE TASKS
Questions provide opportunities for developing skills that you have learnt
about in the demo tasks.

CHALLENGE TASKS
P
Challenge tasks will stretch and challenge you even further.
M
SUMMARY

There is a summary of key points at the end of each chapter.

END-OF-CHAPTER TASKS
A

Questions at the end of each chapter provide more demanding programming tasks, some of which may require
use of knowledge from previous chapters. Answers to these questions can be found in the solutions chapter, on the
digital part of this resource.

NOTE: As there are some differences in the way programming statements are
S

structured between languages, you should always refer back to the syllabus pseudocode
guide to see how algorithms will be presented in your exam.

xi
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

How to use this series


The coursebook provides coverage of the full Cambridge IGCSE,
IGCSE (9–1) and O Level Computer Science syllabuses (0478/0984/2210) for
first examination from 2023. Each chapter explains facts and concepts and

LE
uses relevant real-world contexts to bring topics to life, including two case
studies from Microsoft® Research. There is a skills focus feature containing
worked examples and questions to develop learners’ mathematical,
computational thinking and programming skills, as well as a programming
tasks feature to build learners’ problem-solving skills. The programming tasks
include ‘getting started’ skills development questions and ‘challenge’ tasks
to ensure support is provided for every learner. Questions and exam-style
questions in every chapter help learners to consolidate their understanding.

P
The digital teacher’s resource contains detailed guidance for all topics
of the syllabuses, including common misconceptions to elicit the areas
where learners might need extra support, as well as an engaging bank of
lesson ideas for each syllabus topic. Differentiation is emphasised with
advice for identification of different learner needs and suggestions of
M
appropriate interventions to support and stretch learners.
The digital teacher’s resource also contains scaffolded worksheets
for each chapter, as well as practice exam-style papers. Answers are
freely accessible to teachers on the ‘supporting resources’ area of the
Cambridge GO platform.
A

There are three programming books: one for each of the recommended
languages in the syllabuses – Python, Microsoft Visual Basic and Java.
Each of the books are made up of programming tasks that follow a scaffolded
S

approach to skills development. This allows learners to gradually progress


through ‘demo’, ‘practice’ and ‘challenge’ tasks to ensure that every learner is
supported. There is also a chapter dedicated to programming scenario tasks to
provide support for this area of the syllabuses. The digital part of each book
contains a comprehensive solutions chapter, giving step-by-step answers to the
tasks in the book.

xii
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).

Chapter 1

Visual Studio

LE
Community P
M
A

IN THIS CHAPTER YOU WILL:


S

• understand the two programming applications used in this book


• understand how to code and save a basic program in console application
• understand how to obtain input data and provide output in console application
• understand how to code and save a basic program in Windows Forms application
• understand how to use the main design windows in Windows Forms application
• understand the format of the event-driven subroutines used in a Windows Forms application.

Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Introduction
The process of creating computer program code has changed considerably since the
early days of computer science, when the first programs were written directly in binary KEY WORD
using punch cards. Integrated
Today we use high-level programming languages. These languages use coding Development
statements that are close to human language. The code statements are then translated Environment (IDE):
to binary before being executed by the computer. The majority of high-level software that helps
programming is completed using an Integrated Development Environment (IDE), which programmers to

LE
provides the programmer with tools that help create, debug and translate the programs. design, create and
Visual Studio 2019 Community is an IDE that helps to generate programs written test program code.
using the Visual Basic programming language.

1.1 Getting Visual Studio 2019


Community for Windows KEY WORDS

Visual Studio 2019 Community is the current version of free developer tools provided by Visual Studio
Microsoft. The IDE supports a wide range of programming languages including Visual 2019 Community:
a version of

P
Basic, Visual C++ and Visual C#. Visual Basic provides an interface that allows students
to develop programming skills while at the same time producing satisfying systems.
Visual Basic also provides programmers with access to a large class library. Classes
are templates that hold prewritten code that support functionality of objects. As your
skills increase, you will be able to use this feature-rich development environment to
produce and publish complex systems. System requirements and download options
the Integrated
Development
Environment (IDE)
produced by
Microsoft used to
create programs
M
can be found on the Microsoft website by searching ‘Visual Studio downloads’. using the Visual
Basic programming
language.
interface: the way in
which a user inputs
data into and receives
information from a
A

computer system.
classes: templates
that hold prewritten
code which supports
the functionality of
objects. All of the GUI
S

elements in Visual
Basic are objects of a
class. The GUI objects
can be created and
manipulated without
the need to write
code as the code
required is already
contained in the class.

2
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
1  Visual Studio Community

1.2 The Integrated Development


Environment
KEY WORDS
Note: Window Forms application is optional content. It is not covered in
the syllabuses. console application:
a command-line
interface provided by
Visual Studio 2019 Community IDE is the free version of a full commercial Visual Studio 2019

LE
programming IDE. It offers many different languages and different formats. Community used
This is useful when developing for different environments such as web design, mobile to create programs
applications or computers. This book only uses two of the applications, console using the Visual
application and Windows Forms applications. Both make use of very similar coding Basic programming
approaches to algorithms but differ in how a user interacts with them. The features are language. This
shown in Table 1.1. interface most
directly matches the
Application Features of the application syllabuses.
Console application Used for creating a program that uses a Windows Forms
command-line interface on a computer running application: a
VB Console App a Windows operating system. This provides a GUI provided by
c:\

VB
(.NET Framework)

Windows Forms application

Windows Forms App


(.NET Framework)
P
textual interface uncluttered by the need to
support a Graphical User Interface (GUI).
Used for creating a forms-based GUI program
on a computer running a Windows operating
system.
Visual Studio 2019
Community used
to create programs
using the Visual
Basic programming
language. Windows
M
Users interact with the program by using a GUI, Forms application
which contains the type of elements we see on is an event-driven
web pages and modern applications. These approach to
elements include areas to input values, buttons programming where
to select options and dropdown menus. subroutines are
The GUI can be customised by the programmer. linked to GUI objects.

We have included additional tasks throughout command-line


A

which require you to use GUI programming. interface: an


This is not required by the syllabuses, but for interface that uses
your own interests and programming skills text on a single
development. We have flagged this each time screen to input data
we include one of these tasks. into a system and
output information
Table 1.1: Features of console application and Windows Forms application from that system.
S

Graphical User
Because console application is the required programming format at this level, most of
Interface (GUI):
the code for the demonstration tasks use console application. But all the solutions to
an interface that
the practice tasks are shown in both applications.
includes graphical
elements, such as
windows, icons
and buttons.

3
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

1.3 Getting started


When you first open the IDE, you will see the window in Figure 1.1.

LE
Option
P
Figure 1.1: Visual Studio 2019 home page

The options you might use are described in Table 1.2.

Description
Allows direct opening of programs used recently.
M
Alternatively, you can search for the recent
programs used.

NOTE: The file location shown in the example is the


default repository folder 'source\repos', which is used
for all Visual Studio 2019 programs. Your network
A

administrator may have selected a different folder


location.
Allows you to find and open a Visual Studio program
stored in any folder or external storage device.
This is useful if you are transferring programs between
computers by using external storage devices.
S

Allows you to create a new program in console


application or Windows Forms application.

Table 1.2: Options for using Visual Studio 2019

4
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
1  Visual Studio Community

The ‘Create a new project’ window provides the option to create any of the many
applications provided by the IDE. To reduce the available options, select Visual Basic
from the languages drop-down menu, shown in Figure 1.2.

LE
P
Figure 1.2: Create new project window

The two applications you will be using are shown in the list of available applications.
M
The applications may not appear at the top of the list as shown in Figure 1.2.
NOTE: Be careful when selecting the console applications. There is another console
application for use with macOS and Linux operating systems on the list. This is called
Console App (.NET Core)
You require Console App (.NET Framework)
A

1.4 Console application


When you start a new console application program, you will be prompted to name the
project (see Figure 1.3). It is good practice to give all projects meaningful names.
Defining the name of the project using the ‘Project name’ box will change the Solution
name to match the project name. It is possible to have several projects within one
S

solution, but this is beyond the scope of this book.


This window allows you to select an alternative storage location for your project if you
do not wish to use the default ‘source\repos’ folder.

5
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

LE
Figure 1.3: Configure your project window

P
The default layout of the console application consists of the main programming
window (see Figure 1.4). This provides an area in which you write all the program code
required to accept inputs, process data and display the required outputs. The Solution
Explorer on the top right-hand side of the window displays the contents of a solution.
A solution holds all the components of a project. Our projects will be limited to a
M
single module of code, which will be called Module1. You can see that shown in the
Solution Explorer as Module1.vb. If you accidently close your code window you can
reopen it by double clicking on Module1.vb in the Solution Explorer.
A
S

Figure 1.4: Console application programming window

6
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
1  Visual Studio Community

Although it is much more complex than we will need, it is possible for


Solutions to contain many modules and linked files. Solution Explorer provides
a complete view of the files in a project and can be used to add or remove
files and to organise files into subfolders. Remember, Visual Studio can be
used for large commercial projects and Solution Explorer is very helpful in
those types of project.

1.5 Make your first program using

LE
console application
When the console application is first loaded the code window will contain four lines
of code.
Module Module1
Sub Main()
...
End Sub
End Module
KEY WORDS

P
Modules contain code and can hold a number of subroutines that perform specific
actions. You will learn more about subroutines in Chapter 7. Sub Main() is the
entry point for the program, and End Sub indicates the end of the subroutine.
Code written between these points will be executed when the application is run.
You can use the Enter key to add additional lines.
subroutine:
subroutines provide
an independent
section of code that
can be called from
M
another routine
TIP while the program
Do not change the name of the module Module1 or the subroutine Main( ). is running. In this
These are the module and subroutine that the project will run when it is way, subroutines can
executed. If the module or subroutine does not exist, the project will not run. be used to perform
common tasks within
a program.
Our first program will display the text ‘Hello World’. You need to code the application
execute: in
A

to display the required text. This is the code we will be using. The explanations are in
Computer Science,
the steps below.
the term ‘execute’
Module Module1 means the operation
Sub Main() of a computer
Console.WriteLine("Hello World") program. When a
Console.ReadKey() computer program
S

End Sub is in operation it is


End Module being executed. The
term ‘run’ is also
used to describe the
same process. The
‘program is running’
or the ‘program is
being executed’ both
mean the same thing.

7
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Step 1a
Console.WriteLine("Hello World")
Type the word ‘Console’ into the Main subroutine shown in
the code window (see Figure 1.5).
As you type you will notice that the IDE provides an
autocompletion window listing all the code inputs or objects
that match the letters you have typed. To autocomplete
the entry, you can double click the correct item, or press

LE
the spacebar when the item is highlighted. This will speed
up your coding as once you have typed in the first few
characters of the instruction, the software will automatically
highlight the closest match.

Figure 1.5: Autocompletion window


Step 1b
.WriteLine("Hello World")
In Visual Basic, the functionality of a class is accessed by
use of the dot symbol. When the program reads inputs and
displays outputs, it makes use of the Console class. The

P
Console class provides access to a library of methods that
allow the user to interact with the console.
When Console has been completed type a dot symbol. This
will show a list of all the available methods for the Console
class (see Figure 1.6). The method we need is ‘WriteLine’,
which will display text in the console window when the code
M
is executed. The method must be passed with the required
text: "Hello World".
NOTE: The text to be included is in quotation marks to
indicate that it is text and not a reference to another object.

Figure 1.6: Methods list


Step 2
A

Console.ReadKey()
The code  Console.WriteLine("Hello World") will display the required text
in a console window when the application is run but the window will close as soon
as the code has been executed. To prevent this, use the console ‘ReadKey’ method to
pause the execution until a key is pressed on the keyboard.
S

8
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
1  Visual Studio Community

TIP
Typing Imports System.Console at the start of the program means you
won’t have to type console when you use the class:
Imports System.Console
Module Module1
Sub Main()
WriteLine("Hello World")
ReadKey()
End Sub

LE
End Module
In this code, the Console class is imported at the beginning of the program.
This means that rather than having to write Console. … for both lines of
code in Sub Main(), you can just write the methods needed (in this case,
WriteLine("Hello World") and ReadKey()).

Step 3
To run the code, click the Start option on the toolbar Start or use F5 from the

P
keyboard. This will launch the console window (Figure 1.7) and display the text
‘Hello World’. The execution of the code will be halted until a key is pressed, at which
time the window will close.
M
A

Figure 1.7: Console window

While the console window is open, you may notice the Diagnostic Tools
running in the background (see Figure 1.8). This provides information about
the memory and CPU usage of the program being executed. While this is
helpful when designing commercial projects, it is outside the scope of the
S

syllabuses, and I usually shut the window.

9
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

LE
Figure 1.8: Diagnostic tools window

Congratulations! Your first console application program is complete.


Use the  Save All option under the FILE menu to save your project.

Note: Windows Forms application is optional content. It is not covered in


the syllabuses.

1.6 Windows Forms application P


Console application makes use of a single user interface to accept text-based inputs
and display text-based outputs. Windows Forms application makes use of a range of
Graphical User Interface (GUI) tools, to produce systems that have more in common
with commercial applications.
M
Windows Forms application is more complex as programmers need to design and
produce the graphical user interface that will allow the user to interact with the system.
Visual Basic is an event-driven procedural language in which events trigger subroutines
that execute the code within them.
In Visual Basic, user-controlled events – such as pressing the Enter key or selecting a
button on a GUI – control the execution of the code. This is known as event-driven
programming. A common element of a Windows Forms application GUI is a button
A

that can be selected by a user. When the button is selected, it will trigger the execution
of code held in a subroutine that is linked to the button. As you develop more complex
projects your GUI will include many different buttons that a user can select, each
button triggering a different section of code held in a subroutine linked to that button.
For example, a reset button would be linked to a subroutine that holds the code
required to reset the project.
S

In this first Windows Forms application, we will have a single button. Clicking this
button on the form will trigger the code in the subroutine linked to the button that will
deliver the message ‘Hello World’.
To create a Windows Forms application, you will need to first create a new project
(Figure 1.2) and select Windows Forms App (.NET Framework). You should give
your project a meaningful name and select an appropriate storage location when you
configure your project (Figure 1.3).
The default layout of a Windows Forms application contains five main areas, these are
shown in Figure 1.9 and described in Table 1.3.

10
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
1  Visual Studio Community

Design and programming window Solution Explorer

LE
P
M
Toolbox Error List window Properties window

Figure 1.9: Windows Forms application programming interface

If your Windows Forms application interface does not include all of these windows,
or if you accidentally close a window, you can open additional windows by using the TIP
View option on the top ribbon menu. Individual windows
A

An alternative to opening individual windows via the View option is to return to the on the interface can
default layout. This can be accessed via the Window option on the top ribbon menu be sized, docked
(see Figure 1.10). or set as floating.
You can personalise
the display of the
interface to suit your
own preferences. If
S

you have dual-screen


display, you can have
different interface
windows on different
displays.

Figure 1.10: Default windows layout

11
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

It is likely that when you first access the interface the Toolbox will be minimised. If the
toolbox is minimised, it can be seen on the left-hand side of the interface (indicated by
the red circle in Figure 1.10).
When designing, a good idea is to pin the toolbox menu so that it remains open on
the interface. If you do not do this, each time you move onto another element of the
interface, the toolbox will minimise. This can be achieved by selecting the pin icon
(indicated by the red circle in Figure 1.11).

LE
Figure 1.11: The Toolbox pin icon

The toolbox contains nine different folders of available tools. If you open the
All Windows Forms folder you will see all the available options.
It is unlikely that you will need to use any GUI elements beyond those held in the
Common Controls folder. For our first form we will be using the Button and Textbox
P
elements (indicated by red ovals, Figure 1.12).
M
A

Figure 1.12: Toolbox folders


S

Window Description
Design and Provides an area in which you design the interface for your system and write the program
programming code required to accept inputs, process data and produce the required outputs.
Toolbox Provides a set of tools that will allow you to use a predefined visual GUI and control
objects for the application you wish to develop. You can use your mouse to drag and
drop any of the GUI options in the toolbox onto the form.

(continued)

12
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
1  Visual Studio Community

Window Description
Properties Used to view and edit the configuration of selected objects. The Properties window shows
the current properties of the current GUI object selected (for example, font type and
size, colour, etc.). Changes to the properties of the object can be made by changing the
options in the properties window.
The properties of each element shown are those that are set before the program is
executed. Any changes made during the execution of the program will be lost when the
program is exited. For example, if a you wrote code to change the colour of a button
when a user clicked on it, the button would return to the colour shown in the Properties

LE
window when the program was restarted.
NOTE: The name of the GUI object currently selected is shown at the top of the window.
Ensure you have selected the required object before making changes.
Solution Explorer Displays the contents of a solution, which includes the forms and other project items. This
is where you will find your forms and the program files that support them. It is possible
to have multiple forms within one project; Solution Explorer will allow you to select
individual forms.
Error List Displays any errors, warnings or messages produced as you edit and execute code.
Table 1.3: Description of each window in the Windows Forms application programming interface

P
1.7 Make your first Windows Forms application
In a Windows Forms application, the ‘Hello World’ program will be achieved in
two steps:
M
1 design and construct the user interface
2 code the program that will generate the required output.
NOTE: The code window is activated by double clicking on the form itself or any GUI
object on the form. Soon we will deliberately activate the code window, but if you do
this by accident, you can easily navigate back to the forms interface.
A
S

Figure 1.13: Code tabs

The code tab Form1.vb and design tab Form1.vb (Design) are both shown in the
design and programming window (Figure 1.13), and selecting tabs allow you to swap
between views.

13
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Designing the interface


As with many other design applications (for example, website builders), the Windows
Forms application allows you to design your graphical user interface using a drag and
drop technique rather than writing code. You will have to code what the interface does
later once you have designed it.
Find the button object ab Button in the Toolbox. Click to select the tool and move
the mouse over the form in the main design window. The mouse icon will change
to show the icon of the selected tool. Click and drag will generate a button on the
form. Using the standard Windows mouse controls, it is possible to resize and move

LE
the button.
Use the same process to generate a textbox object abl TextBox on the form.
The form will initially look like Figure 1.14. We will customise this by changing the
properties of the individual elements.

P
M
Figure 1.14: Initial form design

It is considered good practice to give objects meaningful identifiers. An identifier is the


name of the object. The default identifier structure is the type of object followed by
a number. The number increases depending on how many objects of that type are on
the form, such as Button1, Button2, and so on. The Properties window provides the
A

interface to change the properties of each object. As you select an object on the form,
or the actual body of the form itself, the Properties window will change to reflect the
properties of the object or form. Objects have many properties that can be configured
by the designer, but we are initially only interested in the properties in Table 1.4.
Use these properties to personalise the button and textbox.
S

TIP
When giving objects identifiers (names), it is good practice to start the
identifier with capital letters that describe the type of object followed by a
meaningful name. For example, BTNShow for the button used to show the
‘Hello World’ message. Putting the type description at the start will mean that
when you type BTN on the code interface, the autocomplete will show all the
buttons on your form. You could also start the identifiers of all textboxes with
the letters TB followed by a meaningful name.

14
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
1  Visual Studio Community

Property Description
The identifier (name) that
will be used to refer to
the object.
The font style that will used
to display text on the object.

LE
The text (currently Button1)
that will appear on
the object.

The background colour of


the object.

Table 1.4: Descriptions of properties being used

P
To change the properties of individual elements you must select the required element.
You will know which element you have selected because the name will be shown at the
top of the properties window (Figure 1.15).
M
Figure 1.15: Properties identifier

NOTE: If you accidently double click on an element you will activate the code window.
You can easily navigate back to the design window (see Figure 1.13).
A

Figure 1.16 shows the final design of the form.


The button name has been changed to BTNShow from the default value of Button1.
The text on the button has been changed to ‘Show Message’ from the default value of
‘Button1’. The size of the text has also been increased to 12 pt from the default value
of 8.25.
S

The textbox name has been changed to TBMessage from the default value of
TextBox1. The font size of the textbox has also been increased to 12 pt.

15
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

LE
Figure 1.16: Customised form

The background colour of the form has been changed to green using the Custom TIP
colour pallet (Figure 1.17).
Make sure you
have selected the
correct element by
checking the name
at the top of the
properties window.
If you do not it is
possible to change
P
Figure 1.17: The BackColor property custom colour pallet

Code the program


the properties of the
wrong element.
M
To create or edit the program code that will be activated by the form you have
designed, you will need to open the code window.
A

Figure 1.18: Opening the code window

To open the code window, select Code from the View menu (Figure 1.18). The code
window will open as an additional tab in the main design window. Clicking the tabs
will switch between design and code windows (Figure 1.19).
S

Figure 1.19: The code window

16
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
1  Visual Studio Community

The code window will contain only two lines of code. However, this code is important
as it indicates the start and end of the code attached to the form. All additional code TIP
will be placed between these two indicators. Generally, code placed outside will not be Double clicking
part of the form and will cause an error. The Enter key can make additional lines. an object on the
In Visual Basic, user-controlled events – such as pressing the Enter key or selecting a form to generate a
button on a GUI – control the execution of the code. This is known as event driven subroutine can be
programming. A common element of a Windows Forms application GUI is a button done by mistake. This
which can be selected by a user. When the button is selected it will trigger the execution could mean that if
of code held in a subroutine that is linked to the button. you have accidentally
double clicked on an

LE
In this first program, clicking the button on the form will trigger the execution of code object, your program
held in a subroutine linked to the button that will deliver the message ‘Hello World’. will contain unused
Before writing code, the event subroutine linked to the button has to be created. event subroutines. It
The simplest way to create a subroutine is to double click the object on the interface you is a common mistake
wish to use as a trigger (in this case, the button on the form). This will automatically create to place the correct
the code for the default subroutine attached to the object selected and show the code code in the wrong
window. event subroutine. If
your code does not
Public Class Form1
run as expected,
P rivate Sub BTNShow_Click(sender As Object,
check you have used
e As EventArgs) Handles BTNShow.Click
the correct event
End Sub
subroutine.
End Class
P
Let us examine the code to identify what each element achieves (Table 1.5).

Note: Although this makes use of object-oriented language and is outside of


the scope of the syllabuses, it is useful to have some understanding of how
M
the process works.

Code Element Description


Private Sub The start of an individual subroutine. Private means that the subroutine is
only accessible by this form.
BTNShow_Click The name of the subroutine. The automatic default is to name the routine
after the object and event that will trigger the subroutine. However, it is
A

possible to rename the subroutine.


(sender As Object, The arguments, or data, that are associated with the event. As this is a button
e As EventArgs) click event, the arguments are limited – either the button was clicked, or it
was not. However, events associated with mouse activation, for example, will
hold data about the location of the mouse on the form and which mouse
button was clicked. You should not change or delete any of this data as your
S

subroutine might not work. As you become a more advanced programmer,


you will learn how you can manipulate these sections.
Handles BTNShow.Click The event that will trigger the subroutine. In this case, clicking BTNShow will
call the subroutine and execute the code it contains. It is possible to have a
single subroutine triggered by multiple events.
End Sub The end of the subroutine. All the code that is to be executed when the
subroutine is called is placed between Sub and End Sub.
Table 1.5: Breakdown of code elements

17
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

We can now start to write some code. Within the Button Click subroutine, type in the
identifier (name) of your textbox. In this example, the identifier of the textbox has
been changed to TBMessage. As you type, you will notice that Visual Basic provides an
autocompletion window (Figure 1.20) listing all the code inputs or objects that match
the letters you have typed. You can double click the correct item or press the spacebar,
to autocomplete the entry.

LE
Figure 1.20: Autocomplete window

When the name of the textbox has been entered, type a dot symbol.

P
As the textbox is an object of the Textbox class, this will show a list of all the available
methods that can be attached to a textbox object. The method we need is the Text method,
which will either set text into a textbox or get text from a textbox. Fully type the word text,
or alternatively double click or press the spacebar to select the method (Figure 1.21).
M
A

Figure 1.21: Autocomplete methods list


S

To indicate the actual text that should be displayed complete the code:
Public Class Form1
Private Sub BTNShow_Click(sender As Object,
e As EventArgs) Handles BTNShow.Click
TBMessage.Text = "Hello World"
End Sub
End Class
NOTE: The text to be included is in speech marks to indicate that it is new text and not
a reference to another object.

18
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
1  Visual Studio Community

LE
Figure 1.22: Hello World

To run the code, click the Start option on the toolbar Start or select F5 from the
keyboard. This will launch the form as a separate interactive window. Click on the
button and the text ‘Hello World’ will appear in the textbox (Figure 1.22).
In Figure 1.22, the background colour of the form has been changed. Also, the text on
the button has been changed to read ‘Show Message’ and the font of both the button
and textbox to be larger than the default 8.25 pt.

Unlike a console application, the


form will not automatically shut.
It is a common mistake to try and
P
alter code while the program is still
running. To close a form, use the exit
symbol in the top right corner of the Figure 1.23: Debugging icon
M
form. Alternatively, select the Stop
Debugging icon (Figure 1.23) on the
main menu.

Your first Windows Forms application program is complete. You have made use of
the design window and the Toolbox to create the interface. You have generated a
subroutine called by the Click method of a Button object. Within that subroutine you
A

have used the Text method of a Textbox object to place programmer-defined text into
the textbox.
Use the  Save All option under the FILE menu to save your project.

1.8 Choosing a console application or


S

Windows Forms application


Throughout this book, the various tasks are completed using one or sometimes both
of these applications. All the solutions are provided using both methods.
Console applications offer the benefit of reflecting more accurately the programming
style of the syllabuses. Console applications do not involve the additional complexity
of having to reference objects from GUI forms.

19
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Windows Forms applications will offer a richer visual experience and produce systems
similar to those commercially available.
Making use of both applications will best support the development of your
computational thinking.

1.9 Additional support


This book aims to introduce programming concepts, making use of the non-

LE
language-specific formats included in the syllabuses. Visual Basic is used to provide
the opportunity for you to use a real programming language to develop your
understanding of these concepts. Additional support and guidance on the Visual Basic
programming language and Visual Studio 2019 Community can be accessed directly
from the Microsoft Virtual Academy.
A range of video tutorials and links to other support can be accessed from Microsoft’s
Visual Studio website. Just search for ‘Microsoft Visual Studio getting started’.

SUMMARY

P
Visual Studio 2019 Community is the latest version of the integrated development environment IDE) produced
by Microsoft. The IDE provides a set of tools that are used to design, create and debug programs using the
Visual Basic programming language.
Visual Basic makes use of classes which hold prewritten code that supports the functionality of elements
M
used. For example, the console class allows data to be read using console.readline() or displayed using
console.writeline. All of the GUI elements in Visual Basic are objects of a class. The GUI objects can
be created and manipulated without the need to write code as the code required is already contained in the class.
The Visual Studio 2019 Community IDE allows for programs to be created using either a console application
or a Windows Forms application.
• Console application is a text-based command-line interface, that most directly matches the syllabuses.
The code is produced using a single programming interface. When the code is executed the user-interface
A

is a single window used to input data into a system and output information from that system.
User interaction with the program is text based.
• Windows Forms application is a rich, event-driven programming environment that supports a graphical
user interface (GUI). The design of a program requires the development of the GUI. Elements of the
GUI are linked to subroutines in which code is written to perform the required tasks. When the program
is executed the user interacts through the use of elements such as buttons and text buttons on the GUI.
Information output from the system is also shown on the GUI. The GUI can be customised by the
S

programmer to suit the needs of the system.


Subroutines are used in both applications to contain instructions relevant to a specific task. The subroutines can
be triggered by user interaction such as pressing the Enter key or clicking a button on the GUI.

20
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).

Chapter 2

Programming

LE
constructs P
M
A
S

IN THIS CHAPTER YOU WILL:


• learn the difference between the three programming constructs: sequence, selection and iteration
• understand the role of flowcharts and pseudocode when designing programs
• understand the main symbols used in flowcharts
• learn about the preferred format of pseudocode.

Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Introduction
Many sporting activities make use of a limited range of approaches. Racket sports –
KEY WORD
such as badminton, for example – consist of a surprisingly limited number of different
shots. Drop shots close to the net, long cleared shots to the back of the court and hard- construct: a method
driven shots account for a large proportion of the shots used in a game. The skill is in of controlling the
combining those shots effectively to win the game. order in which
Programming also makes use of a limited range of constructs to achieve satisfactory the statements in
solutions to complex tasks. Like a good badminton player, who combines different an algorithm are
executed.

LE
shots to win a game, an effective programmer will combine different constructs to
produce efficient programs.

2.1 Programming concepts


Visual Basic and other procedural languages make use of three basic programming
constructs (Table 2.1). Combining these constructs provides the ability to create code KEY WORDS
that will follow a logical process. sequence: code is
executed in the order
Sequence The order in which the code is executed.
it is written.
Selection Providing options that will allow the execution (running) to follow a

Iteration
P
different path through the program based on certain criteria.
Repeating a sequence of steps during the execution of the code.
Table 2.1: Programming concepts

In Computer Science, the term ‘execute’ means the operation of a computer program.
selection: code
follows a different
sequence based on
what condition is
chosen.
M
iteration: code
When a computer program is operating, it is being executed. The term ‘run’ is also
repeats a certain
used to describe the same process. The ‘program is running’ or the ‘program is being
sequence a number
executed’ both mean the same thing.
of times depending
on certain conditions.
Sequence
The order in which a process is completed is often crucial to the success of that process.
TIP
A

Take the mathematical expression A + B × C + D. The rules of precedence dictate that


the multiply operation (B × C) will be completed first. Had the programmer wanted The mathematical
A + B and C + D to be completed before multiplying the two resultant values then rule of operation
they would have had to be explicit about the required sequence: (A + B) × (C + D). precedence,
To calculate the time it takes to complete a journey, you need to know the distance to commonly known
be travelled and the speed you will travel. The first logical step would therefore be to as BODMAS, also
applies to operators
S

calculate the distance to be travelled as, without this data, you could not complete the
rest of the task. used in programming
in the same way it
Most tasks will involve different steps, and those steps often have to be completed applies to normal
in some logical sequence. When designing computer programs to achieve tasks, it is mathematical
crucial to consider the sequence in which the task needs to be completed. calculations.

22
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
2  Programming constructs

For example, when a satnav calculates an estimated arrival at destination time,


the process follows a series of logical steps:
Step 1   Obtain location of journey start point.
Step 2   Obtain location of journey end point.
Step 3   Calculate shortest route between the two points.
Step 4   Calculate the time it will take to complete the journey.
Step 5   Obtain the time the journey will start.
Step 6  Calculate the estimated arrival time by adding the journey time to the start time.

LE
Obtaining the journey start and end points is crucial because without this information,
the rest of the process could not be completed. However, the order in which the two
locations is obtained is not that important. Had Step 1 and Step 2 been reversed,
the calculation at Step 3 could still have taken place.
In programming, the sequence is indicated by the order in which the code is written,
usually top to bottom. The program will execute the first line of code before moving to
the second and subsequent lines. An example of a sequence error would be completing
a process before all the appropriate user inputs had been obtained. For example,
trying to calculate the area of a rectangle when you only had the length of one side.

Selection
P
Often your programs will perform different processes dependent on user input.
Consider a system designed to provide access to the school network when a user inputs
a username and password. The system would need to follow different paths depending
on whether the user input was accurate or not.
M
One path would be followed if the username and password input matched records that
would allow network access. If the username and password input did not match the
records, the system would follow another path in which the network access would be
denied and the user prompted to re-input the details.

Access denied and User Name inputted


user prompted for Incorrect and checked against Correct Access granted.
new password. password.
A

Figure 2.1: Different paths needed on input of username to access school network

Iteration
S

It is common for a program to perform identical processes on different data items.


Consider a program that produces a line graph. It takes a series of coordinates and draws
a line. The code that provides the instructions that plot the new coordinates and draws a
connecting line from the previous coordinates will be repeated for each coordinate given.
Iteration allows the execution of the code to jump back to the beginning of the code
sequence that provides instruction on how to ‘plot’ every time a new set of coordinates
is entered.

23
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

2.2 Design tools


When you design programs, it is normal to plan the logic of the program before you start
to code the solution. This is an important step in the design of effective systems because
a flaw in the logic will often result in programs that run but produce unexpected outputs.
The first step in the design process is to break down the problem into smaller problems.
This is called top-down design. Once you have the smaller problems defined then you KEY WORDS
can consider each problem separately. This will be easier to plan and finally code. You
top-down design: a
can use a structure diagram to help organise the top-down design. Chapter 6 explains
way of designing a
top-down design and structure diagrams.

LE
computer program
The next stage is to design an algorithm for the individual problems. Two approaches by breaking down
(shown in Table 2.2) that can be used at this stage to help create logically accurate the problem into
systems are flowcharts and pseudocode. smaller problems
(subsystems) until it
Flowcharts A graphical representation of the intended logic and sequence is sufficiently defined
of a program or ‘flow of a program’ (which is where the name to allow it to be
‘flowchart’ came from). It is a diagram that describes the flow that understood and
the execution of code will take through a program. programmed.
Pseudocode A method of describing the logic and sequence of a program using
algorithm: a process
natural language to explain each step in the intended process. The
or set of rules to
logic can be understood by programmers without the need for

P
detailed knowledge of any specific programming language. The
term ‘pseudo’ is derived from the early Greek word for ‘false’.
Table 2.2: Algorithm design tools

For this course, you will be expected to have a working understanding of both flowcharts
be followed during
the execution of a
program.
M
and pseudocode and to use them to answer questions that ask you to explain the logic of
your solutions to given tasks. Both methods are used throughout this book to indicate
the logic of systems, and it is important that you become familiar with their use.
KEY WORD
flowchart:
2.3 Flowcharts a graphical
representation of the
Flowcharts are graphical representations of the logic of the intended system. They make sequence and logic
A

use of symbols to represent operations or processes which are joined by lines that indicate of a program.
the sequence of operations. Table 2.3 details the symbols used.

Symbol Notes Examples


Terminator The START or STOP of a system.
S

START STOP

Input or output A required INPUT from the system user or an


OUTPUT to the system user. INPUT OUTPUT
The value being input or output is written on number result
the symbol.
(continued)

24
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
2  Programming constructs

Symbol Notes Examples


Process A process within the system.
The flowchart should show sufficient detail
to indicate how the proposed process is to
be achieved. Beware of making the process
too generic. average ←
result ← A * B
(A+B+C+D)/4
For example, if the system had to calculate an
average value, a process entitled ‘Calculate

LE
Average’ would be too generic. It needs to
indicate the inputs or other values used to
calculate the average.
Logic flow Joins two operations.
INPUT OUTPUT
The arrowhead indicates the direction of A, B
result ←A * B
result
the flow.

Decision A point in the sequence where alternative


forward(100)
paths can be taken. FALSE
repeatIs×Input
4
TRUE
TRUE FALSE =A
Number
The condition on which the flow is

P
determined is written within the symbol.
Where multiple alternatives exist, sequence
flows are indicated by chained decision
symbols. Each ‘FALSE’ condition directs to
another decision.
> 10

FALSE
FALSE
right(90) Is Input

Is Input
=C
=B
TRUE
TRUE
M
Table 2.3: Symbols used in a flowchart

DEMO TASK 2.1 KEY WORD


Use a flowchart to represent the process of calculating an estimated arrival condition: the criteria
time for an aeroplane journey. that are tested as
part of the execution
A

Solution of the code. The


The steps in the process are: condition will result in
either a True or False
Step 1   Obtain location of journey start and end airports. answer when tested.
Step 2   Obtain the distance between the two airports.
S

Step 3   Calculate the time it will take to complete the journey.


Step 4   Obtain the time the journey will start.
Step 5  Calculate the estimated arrival time by adding the journey time to
the start time.
Step 6   Output the estimated arrival time.

25
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

CONTINUED

START

INPUT Start Airport


INPUT End Airport

LE
Obtain Journey
Distance

Calculate
Journey Time

P INPUT Start Time


M
Arrival Time ←
Start Time + Journey Time

OUTPUT Arrival Time


A

STOP
S

Flowchart 2.1: Flowchart for calculating arrival time for an aeroplane journey

This task follows a simple linear process, so the flowchart that represents the
process also follows a single path.
NOTE: Observe the use of the different symbols to indicate the inputs /
outputs from the processes that need to be completed. When you come to
code programs these will help to identify the need to obtain user input.

26
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
2  Programming constructs

Flowchart design
A flowchart is often created in two stages.
Stage 1
Plan the logic and order of the system. The flowchart will show the intended sequence.
It will include the inputs, outputs, decisions and processes required. At this stage, the
process rectangle and decision diamonds are likely to include a text description of the
processes or decision that must be made. There may be little, if any, detail provided
about how the decisions or processes will be completed. This is known as high-level

LE
design and allows the programmer to check the logic of the system.
Stage 2
The decisions and processes will be added to provide details about how they will be
completed. As the design develops, you will be able to consider the factors involved in
each process and include a greater level of detail about each process. At this stage, a
programmer may discover that they need additional inputs to be able to complete the
process effectively. Wherever possible the final flowchart should include well-defined
processes. Effective flowcharts avoid ambiguity.
The arrival time flowchart (Flowchart 2.1) includes examples of both Stage 1 high-level
process and Stage 2 well-defined processes. Details of these processes are shown in
Table 2.4.

Stage
Stage 1
High-level
process
Process P
Calculate time to complete journey
While this description accurately describes the process, it does not
define how to complete the process. It does not define what speed
M
should be used to calculate journey time. Different aircraft fly at
different speeds, so it is likely that the user would be expected to
input the speed to be used. However, this step is not shown.
Stage 2 Arrival Time ← Start Time + Journey Time
Well-defined
process This is a well-defined process. There is little ambiguity about how
to complete the process.
The ← symbol means ‘becomes the result of’. In this example,
A

the arrival time will be the result of adding the journey time to the
start time of the flight.
Table 2.4: Examples of the two stages of flowchart creation
S

27
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

The best practice in symbol detail is shown in Table 2.5.

Symbol Best practice suggestions


Input and output The word INPUT or OUTPUT should be included in the
symbol. As the symbol for inputs and outputs is the
same, this helps to avoid confusion.
The name of the data to be input or output should be
descriptive. Avoid single letter descriptions, such as
INPUT A.

LE
Process A description of the process must be included in the
process symbol.
Complex processes should be broken down into a
series of simple steps, each step being represented by a
different processes symbol.
A process can have only a single outward flow. If a
process had two outward flow lines, which one would
be followed?
Decision A decision will have two outward flows. Where more
than one option exists, a sequence of decisions should
be used.
P
The condition that will control the flow of execution must
be included in the decision symbol.
It is crucial to label the outgoing flows TRUE and FALSE.
If these are missing the direction of flow is not known.
M
Table 2.5: Best practice in symbol detail

PRACTICE TASK 2.1


How would the flowchart in Demo Task 2.1 need to change to show the
calculation of journey time based on a user input of preferred speed?
A

Can you identify any other ambiguities in this flowchart?

DEMO TASK 2.2


Use a flowchart to represent a system that will output the results of an
entrance examination for a university. The system requires the input of the
S

maximum possible score in the examination and the score achieved by the
candidate. Candidates who achieve 80% or more of the maximum score will
be invited for an interview to decide if they will be offered a place at the
university. Candidates who score less than 80% will be rejected.

28
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
2  Programming constructs

CONTINUED
Solution

START

LE
INPUT Max Score
INPUT Candidate Score

Percent ←
Candidate Score / Max
Score * 100

FALSE TRUE

Send Reject Letter


P Percent >= 80 Invite to Interview
M
STOP

Flowchart 2.2: Flowchart to output the results of an entrance examination

NOTE: Observe the use of the diamond symbol to indicate a decision. The
A

criteria are Boolean expressions that will either be TRUE or FALSE. It is crucial
that the TRUE/ FALSE indicators are added to show how the execution of the
code will flow.

PRACTICE TASK 2.2


S

How would Flowchart 2.2 need to change if the university introduced a


process where candidates who achieved more than 90% in the entrance
examination are automatically offered a place at the university without the
need of an interview?
Redraw the flowchart to include this option.

29
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

DEMO TASK 2.3


Use a flowchart to represent a system that checks the entry of a new
password. The user must enter the password twice. If the two entries match
the system will accept the new password and output a message to the user.
If the two entries do not match the system will reject the password and
repeatedly prompt for it to be re-entered until the two password inputs match.

Solution

LE
START

INPUT Password1
INPUT Password2

FALSE
OUTPUT "Passwords do not Password1 =
match, please re-enter"
P Password2

TRUE
M
Accept New
Password

OUTPUT "New Password


accepted"
A

STOP

Flowchart 2.3: Flowchart to check the entry of a new password


S

NOTE: Observe the return flow from the FALSE path of the decision symbol.
A flow that returns to an earlier stage in the flowchart represents iteration.
In this example, the return loop indicates the continual repetition of the steps:
• input password twice
• check passwords match
• if no match prompt for re-entry of passwords.

30
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
2  Programming constructs

PRACTICE TASK 2.3


How would Flowchart 2.3 need to be changed if the requirements for the
acceptance of the new password were altered to include the following?
• The password must contain more than six characters.
• The password must contain at least one symbol.
Redraw the flowchart to include this option.

LE
You only have to include (Stage 1) general descriptions for this flowchart.
You do not yet know how to program the checks required, so a general
description of each check will be acceptable.

SKILLS FOCUS 2.1


COMMON FLOWCHART ERRORS
A system is required that will accept two numbers. The numbers must be larger than
10 and less than 20. Numbers outside of this range will be rejected and the user
asked to re-input values. Once both numbers are within the range the system will

P
output the result of adding the two numbers together.
Consider the attempt at creating a flowchart for the task shown in Flowchart 2.4.

START
M
INPUT
Numbers

OUTPUT
Check in Range
"Not in range
A

10 to 20
re-enter"

INPUT
Calculate Result
Numbers
S

OUTPUT

STOP

Flowchart 2.4: Flowchart attempt

31
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

CONTINUED
The flowchart includes three errors as well as elements that could be better defined.
Before you read on to the next part, which shows the errors and improvements,
see if you can:
1 spot the errors and explain how to correct them
2 suggest the possible improvements.

Errors and possible improvements

LE
While the flowchart may at first glance appear logical it does contain several errors
and ambiguities. Table 2.6 identifies and explains the errors in the flowchart and
Table 2.7 offers some improvements.

This is a process symbol and can have only one outward flow. This
Check in Range symbol should be replaced with one or more decision symbols.
10 to 20
Not only is the wrong symbol used, there are no TRUE or FALSE
options to indicate the direction of flow.
OUTPUT This attempt at a loop will cause the user to enter new numbers.
Check in Range
"Not in range However, it will only check the numbers once. If the user inputs
10 to 20

Calculate Result
re-enter"

INPUT
Numbers
P incorrect numbers a second time, the numbers will not be checked.
The task stated ‘Once both numbers are within the range’, so this does
not achieve the task requirements .
M
This is the correct symbol but does not show what is being output.
OUTPUT It should show OUTPUT Result.

Table 2.6: Errors in the flowchart

This does not indicate how many numbers should be input.


A

INPUT Numbers It would be improved by indicating the two numbers as individual inputs. Either by
using two input symbols or by writing two INPUT descriptions in one input symbol.

Although this process is accurately described, it is not well defined. It does not
Calculate Result show what calculation should take place.
S

When replacing this incorrect symbol with decision symbols, the level of detail
Check in Range should be considered. Currently there is ambiguity in the words used. It does not
10 to 20 define whether the check should include the values 10 and 20 or whether they
should be excluded from the range.
This can be made clearer through using the mathematical > and < symbols.
Table 2.7: Improvements

32
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
2  Programming constructs

CONTINUED TIP
The corrected flowchart now looks like Flowchart 2.5. When writing the detail in
the decision symbols, make
sure you include precisely
START
defined mathematical
conditions. These should be
defined using appropriate
mathematical symbols such
as > or <. Using terms such

LE
as ‘greater than’ or ‘less
INPUT Number1
than’ should be avoided.
INPUT Number2

TRUE TRUE TRUE TRUE


Number1 > 10 Number1 < 20 Number2 > 10 Number2 < 20

FALSE

OUTPUT
"Not in range
P FALSE FALSE FALSE
M
re-enter"

Result ←
Number1 + Number2

OUTPUT
A

Result

STOP
S

Flowchart 2.5: A correct flowchart for the two numbers task

The INPUT symbol now shows that two numbers need to be input.
The incorrect process ‘Check in Range 10 to 20’ has been replaced with a series of
decision symbols. Each decision defines the range being checked precisely.

33
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

CONTINUED
Any incorrect entry is shown the error message and redirected back to the INPUT
symbol. This process will continue to repeat until two in range values are input.
The result process shows the exact process to be completed and the final OUTPUT
symbol defines the value to be output.

Questions
A scenario question is likely to use words to describe acceptable range values.

LE
You will be expected to use precise mathematical terms to define the
range in a flowchart.
For the following scenarios, create an appropriate flowchart. Consider what inputs
are required and what values need to be checked. Remember to be precise when
defining the limits.
1 A roller-coaster has height and weight restrictions. To be able to ride the
roller-coaster people must be at least 1.10 metres tall. The maximum weight a
seat on the roller-coaster can safely hold is 125 kilograms. Only people who are
within these limits will be permitted to rider the roller-coaster.
2 A firm makes metal beams. Beams come in two strengths ‘standard’ and

3
P
‘extra strong’. The minimum length of beam they will make is 1 metre.
A standard beam can be no longer than 4 metres, but an extra strong beam can
be made in lengths up to 6.5 metres. Orders for beams outside of these limits
will be rejected. All other orders proceed to a process called ‘Calculate Price’.
A climate control system in a hospital operating theatre is required to maintain
a constant temperature of 21° Celsius. A temperature sensor inputs the actual
M
temperature in the operating theatre into the system. If the actual temperature
drops below 20° Celsius, the heating must be on. If the actual temperature rises
to 22° Celsius or more, the cooling system must be on. When the actual
temperature is between these two limits both the heating and cooling system
are off. Remember the temperature is constantly being checked.
A

2.4 Pseudocode KEY WORD


Pseudocode is a method of describing the logic and sequence of a system. It uses pseudocode: a way
keywords and constructs similar to those used in programming languages but without of unambiguously
the strict use of the syntax required by formal languages. It allows the logic of a system representing the
to be defined in a way that is independent of any specific programming language. sequence and
S

logic of a program
Pseudocode can be understood by any programmer. This means that the final program
using both natural
can be coded using any programming language that is appropriate to the context.
language and
This is useful when designing programs as the code required to perform a particular code-like statements.
process can vary considerably across differing programming languages. It also means
that if there are multiple people working on a project, programmers from different
programming language backgrounds can discuss and develop ideas and logic using a
format common to them all.

34
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
2  Programming constructs

Pseudocode follows a number of underlying principles:


• Use capital letters for keywords close to those used in programming languages.
• Use lowercase letters for natural language descriptions.
• Use indentation to show the start and end of code statements, primarily when
using selection and iteration.
• Pseudocode should always include comments to explain the logic of the
algorithm. A comment in pseudocode is defined by starting with the symbol //
One advantage of learning to program using Visual Basic is that the actual coding

LE
language is structured in a similar way to natural language and therefore closely
resembles pseudocode. Visual Basic also automatically indents instructions where
appropriate similar to the approach that should be adopted when writing pseudocode.

Pseudocode example
This pseudocode is for an algorithm that accepts the input of two numbers.
These values are added together and the result is stored in a memory area called Answer.
The value in Answer is then displayed to the user. (In Chapter 3, you will learn that this
memory area is known as a variable.)
// Entering the values
INPUT Number1
INPUT Number2
P
// Calculate the addition and store in Answer
Answer  Number1 + Number2
// Output the value in Answer
OUTPUT Answer
M
NOTE: Observe the use of ← to show the passing of values. This is distinct from the
use of the equals symbol (=), which is used to indicate a comparison of two values.
(Visual Basic does not have the ← symbol and uses the = symbol in both situations.)

2.5 Use of flowcharts and pseudocode


A

in programming
Because of the universal nature of flowcharts and pseudocode, they are used
extensively in the design of computer programs. The aim of this book is to help you
to learn to design effective systems using the programming language Visual Basic.
The following chapters make use of flowcharts and pseudocode to define the logic of
S

systems, before moving on to specific Visual Basic-coded solutions.


Learning how to detail the logic of programs through the use of these design
techniques will be a crucial step in your preparation for using the languages of the
future. Language syntax is likely to change in the future but the need for effective
logical and computational thinking will remain a constant.

35
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

CHALLENGE TASKS 2.1–2.2


2.1 A system is required by a teacher to calculate grades in an examination.
The teacher will input the maximum marks that could have been achieve
in the examination and the actual mark achieved by the student.
The system will output the grade based on these boundaries:
Grade as Distinction if percentage above 80
Grade as Merit if percentage in range 61–80

LE
Grade as Pass if percentage in range 40–60
Grade as Fail if percentage less than 40.
Design a flowchart to show the logic of the system required to output the
correct grade.
2.2 A program is needed to work as a calculator. The user is asked to input
two separate numbers and an arithmetic operation (+ , ×, ÷ or −).
The program must then calculate the answer. This answer must be output.
Design a flowchart to show the logic of the system required to complete
this task.

SUMMARY
P
Programmers make use of three constructs when writing code:
M
• sequence: the logical order in which the code is executed
• selection: branching of code onto different paths based on certain conditions
• iteration: repeating of sections of code.
Before coding a program it is crucial to design an appropriate algorithm using either a flowchart or pseudocode.
Flowcharts use a series of symbols to visually represent the logic of a program. The flow of the execution of the
program is represented by flow lines with arrow heads to show the direction of flow. It is crucial that the correct
A

symbols are used. The examination board will provide a flowchart guide and you must become familiar with the
expected symbols.
Flowchart design can be done in two stages:
• the first stage is to consider the logic steps and processes required for the algorithm
• the next step is to consider how those steps could be achieved and ensure the flowchart contains enough
S

detail to fully describe each step.


Decision symbols in flowcharts need to include precisely defined mathematical conditions. These should be defined
using appropriate mathematical symbols such as > or <, for example, use A < B rather than A is less than B.
Pseudocode is a method of describing the logic of a program by using written language. The language used
includes a series of key words that describe the exact programming constructs used in the program.
It is important that you comment your pseudocode (using the // symbol) to help explain the logic of your algorithm.

36
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.
We are working with Cambridge Assessment International Education towards endorsement of this title.
Any references or material related to answers, grades, papers or examinations are based on the opinion of the author(s).
2  Programming constructs

END-OF-CHAPTER TASKS
1 State the definitions of the following terms:
• an algorithm
• sequence
• selection
• iteration.
2 Explain what the following flowchart symbols are used for:

LE
     

3 Create a flowchart to show the logic of the algorithm for this system:
A user is required to input two numbers into the system. The second number must be exactly double the
first number.
The system will check that the second number is double the first. If this is not true, the system will output a
message and the user must re-enter the numbers. This process will continue until the second number is exactly
double the first.
P
When this happens, the system will output the addition of the two numbers.

4 A business supplies sand to building sites. The delivery truck used has a maximum weight limit of 12 tons so
no order greater than 12 tons can be accepted.
Sand is provided in two different qualities:
M
Soft Sand Charged $40.00 per ton (or part of a ton)
Sharp Sand Charged at $36.50 per ton (or part of a ton)

In addition to the cost of the sand a delivery charge of $20.00 is charged.


The system will require the input of the amount and type of sand required. It will check the inputs meet
limits and then output the total cost of the delivery.
Create a flowchart to show the logic of the system required by the sand business.
A
S

37
Original material © Cambridge University Press 2021. This material is not final and is subject to further changes prior to publication.

You might also like