Professional Documents
Culture Documents
• write a program in a high-level language (Python, Visual • use a loop ('count controlled', 'post-condition', 'pre-
Basic console mode, Pascal/Delphi console mode) condition')
• implement and write a program from a given design • justify why one loop structure may be better suited to a
presented as either a program flowchart or pseudocode problem than the others
• write program statements for: • select a suitable data structure (lD or 20 array) to use for
• the declaration of variables and constants a given task
• the assignment of values to variables and constants • write program code to process array data (including
• expressions involving any of the arithmetic or logical bubble sort and linear search)
operators • recognise the basic control structures in a high-level
• input from the keyboard and output to the console language other than the one chosen to be studied in depth
• select appropriate data types for a problem solution • use a subset of the built-in functions and library routines
(integer, real, char, string, Boolean, date) supported by the chosen programming language,
• show understanding of how character and string data are including those used for string/character manipulation,
represented by software including the ASCII and Unicode formatting of numbers, random number generator
character sets • use the information provided in technical documentation
• use an 'IF' structure including the 'ELSE' clause and describing functions/procedures
nested IF statements • show understanding of why files are needed and write
• use a 'CASE' structure pseudocode and program code for simple file handling of
a text file, consisting of several lines of text.
- -- - --- - -- -- - -- ----
To w rite a compu ter program, we need to know t he syntax of these basic co nstructs in our
chosen programming language. This chapter int roduces syn t ax for Python , Visua l Basic
console mode and Pascal/Delphi console mode.
You only need learn to program in one of the t hree languages covered in t hi s book. However,
you should be able to recognise the basic control structures in a high-level language oth er
than the one chosen to be studied in depth. So do read the sections covering th e other two
program ming languages.
Python
Python was conceived by Guido van Rossum in the late 1980s. Python 2.0 was re leased in
2000 an d Python 3.0 in 2008. Python is a mult i-paradigm programming language. It ful ly
supports both object-oriented progra mming and structured programm ing. Many othe r
paradigms, includ ing logic programm ing, are supported using extensions. Th ese parad igms
are covered in Chapters 26, 27 and 29.
The Python programs in this book have been prepa red using Pyth on 3 (see www.pyt hon.org
for a free downloa d) and Pyt hon's Integrated Development Environ ment (IDLE).
You can also type prog ram code into a Pyt hon editor (suc h as IDLE), save it w ith a .py extension and then run the
program cod e from the Run menu in the editor w ind ow (see Figure 13.02).
J
print ( "Hello World!" )
>>> RESTART ===
>>>
He llo World!
>>>
Figure 13.02 (a) A saved program in the Python editor window and (b) running in the Python shell
Th e Visual Basic progra ms in this book have been prepared using Microsoft Visua l Basic 2010 Exp ress Console
Application. (Free down load available from www.visualstudio.com/ products/visual-studio-express-vs)
• Eve ry statement should be on a separate line. Statements can be typed on the sa me line
with a colon(:) as a separator. However, this is not recommended .
Indentation is good practice.
• VB .NET is not case sensitive. Modern VB.NET editors wi ll automatica lly copy the case
from the first definition of an identifier.
• The convention is to use CamelCaps (a lso known as Pascal Caps) for identifiers and
keywords.
Programs need to be comp iled (see Chapter 7, Section 7.05 for information on interpreted
and compiled programs).
You t ype yo ur program code into the Integrated Deve lopment Environment (ID E) as show n in
Figure 13.03 (a), save the program code and then cl ick on the Run button (,,!]I). Th is invokes
the compi ler. If there are no syntax errors the compiled program w ill then run. Output wi ll be
shown in a separate conso le w indow (see Figure 13.03 (b)).
...
~ Chapter 13 Programming and Data Representation
EJ Module Modulel
I
El Sub Main ()
l
Console .Write l ine ("Hel l o World !" )
Console . Readline ()
End Sub
100%
-
' .. ( <t
Figure 13.03 (a) A saved program in the VB.NET editor and (b) running in the program
execution (console) window
Note that the console window shuts when the program has finished execution . To keep it
open, so you can see the output, the last statement of your program shou ld be
Console .ReadLine () (see Figure 13.03(a)).
•
encourage good programming practice using structured programming. Pascal was
published in 1970. A derivative known as Object Pascal for object-oriented programming was
developed in 1985. Delphi was originally developed by Borland and uses Object Pascal. Since
2008, Delphi has been owned by Embarcadero Technologies.
The Pascal programs in this book have been prepared using Borland Delphi 7 Console
Application. Other Pascal/Delphi ID Es will work in a similar way (for example, the free version
from www.lazarus.freepascal.org).
Every statement ends with a semico lon(;). More than one statement can go on a single
line, but this is not recommended.
• Indentation is good practice.
• Pascal is not case sensitive.
• The convention is to use Camel Caps (also known as Pascal Caps) for identifiers and lower
case for keywords.
• A compound statement consists of a sequence of statements enclosed between the
keywords begin and end.
• Whenever Pascal syntax requires a statement, a compound statement can be used. For
an example see Table 13.28.
Programs need to be compiled (see Chapter 7, Section 7.05 for information on interpreted
and comp il ed programs).
You type your program statements into the Integrated Development Environment (IDE) as
shown in Fi gure 13.04 (a), save the program code and then cl ick on the Run button
( ~ ). This invokes the compiler. If there are no syntax errors the compiled program code will
then run. Output will be shown in a separate (console) window (see Figure 13.04 (b).
Cambridge International AS and A level Computer Science
Project2 I
p rogram Proj e c t 2;
-...
{$APPTYPE CONSOLE}
uses
Sys Util s ;
• b egin
Writ e Ln (•He l l o World ! •) ;
ReadLn ;
-
• e n d.
..ill
1_ 1 1: 1 .... [~
-~
ln-se-,t- - ~ M
Figure 13.04 (a) A Pascal program in the Delphi editor and (b) running in t he program
execution (co nsole) window
Note that the co nsole window shu t s when t he program has finished execution. To keep it
open, so you can see the out pu t , the last st atement of yo ur program shou ld be ReadLn ; (see
Fi gure 13.04(a)).
Pyt hon ha ndles va riables differently to most program ming languages. It tags values . Thi s is
why Python does not have varia ble decla ratio ns. Howeve r, it is good pro grammi ng practice
to inclu de a co m me nt abou t t he variab les you are plann ing to use and t he t ype of data you
wi ll store in them .
Syntax definitions
The syntax of va riable declarations in language code is as follows:
Code examples
Python # Numberl of type Integer There are no declara t ions, but
# YourName of type String comments should be made at
# Nl, N2, N3 of type integer;
the beginning of a mo dule (see
# Name 1, Name2 of type string;
the secti on abou t comments
at th e end of Section 13.02).
VB.NET Di m Numberl As Integer You can group more than one
Di m Yo urName As String variab le of the same type on
Di m Nl , N2 , N3 As I nteger
the same line.
Di m Namel , Name2 As Stri ng
Pascal v a r Numberl int eger;
: The keyword var can be
var Yo urName s tring; :
repea ted on each line or
var Nl , N2, N3 : integer ;
om itted fo r furthe r lines of
Namel, Name2 : s tring;
•
declarat ions. You ca n grou p
more than on e variable of the
same type on t he same line.
For exa m pl e:
CONSTANT Pi 3 . 14
Syntax definitions
Python <identifier > = <value >
r
Cambridge International AS and A level Computer Science
Code examples
Python PI = 3.14 Python con vention is to write constant
identifiers using all capital letters. The values
can be changed , although you should treat
constants as not changeab le.
VB.NET Const Pi = 3 . 14 The value of a constant in VB.NET cannot be
altered within the program.
Pascal Const Pi = 3 .14; The value of a constant in Pascal cannot be
alte red w ithin the program.
Assignment of variables
Once we have declared a variable, we can assign a value to it (See Chapter 11, Section 11.04).
VB.NET <iden t ifier > = <express i on> A = 34 Th e ass ignment ope rator
B = B + 1
is=.
Pascal <ident ifier > .- <expression>; A .- 34; Th e assignmen t ope rator
B .- B + 1; is a co mbination of a colon
and an eq ua ls si gn without
a space in bet wee n (:=).
VB .NET allows you to initialise a variable as part of the declaration statement, for examp le:
Dim Numberl As Integer= O
Arithmetic operators
Assignments don't just give initial va lues to variab les. We also use an assignment when we
need to store the result of a calculation. The arithmetic operators used for ca lculations are
shown in Tab le 13.01.
Multiplication * * * *
Division I I I I
Exponent
A
**
A
Not available
Integer division DI V II \ Div
Modu lus MOD % Mod Mod
When more than one operator appears in an expression, the order of eva lu ation depends
on the mathematical rules of precedence: parentheses, exponentiation, multiplication,
division, addition, subtraction.
L
~ Chapter 13 Programming and Data Representation
Question 13.01
Evaluate each of the following expressions:
4*3-3"2
(4 * 3 - 3) "2
4 * (3 - 3) "2
4 * (3 - 3 "2)
When outputting text and data to the console screen, we can list a mixture of output strings
and variable values in the print list.
Syntax definitions
Python
VB.NET
print (<printlist>)
print (<printlist>, end = II)
Console.WriteLine(<printlist >)
Cons o le.Write(<printlist>)
Print list items are separated
by commas(,). To avoid
moving onto the next line after
the output, use end =
,,
Print list items are joined using
&. Console.WriteLine will
•
move onto the next line after
the output; Console. Write
will remain on the same line.
Pascal WriteLn(<printlist>); Print list items are separated
Write (<printlist>);
by commas(,) . writeLn
will move onto the next line
after the output; Write will
rema in on the same line.
Code examples
In the examples below, the print list consists of four separate items:
"Hello" and". Your number is" are strings and
YourName and Numberl are variables, for wh ich we print the value.
OUTPUT "Hello 11
, YourName, " . Your number is ", Numberl // newline
OUTPUT "Hello " // no new line
In pseudocode, we can indicate whether a new line shou ld be output at t he end by a
comment at the end of the statement.
In the code examp les above you can see how output statements can be spread over more than
one line when they are very long. You must break the line between two print list items. You
cannot break in the middle of a string, unless you ma ke the string into two separate strings.
In Python and VB .NET you can also use the placeholder method for output: the variables
to be printed are represented by sequentia l numbers in { } in the message st ring and the
variables are li sted in t he correct order after the string, separated by com ma s:
Note t he space between the colon and the closing quote. This is significant. It gives a space
before the user types t heir input.
--- -- -- --------
- -~-- -- - - - ~- --- - -
Comments
It is good programming practice to add comments to explain code whe re necessary.
Python
VB.NET
# this is a comment
# this is another comment
II thi s is a comment
•
II th i s is a no t he r comment
Pascal II this is a comment
II this is another comment
{this is a multi -line
comment}
l TASK13.0l
Use the IDE of your chosen programm in g language (in future just referred to as 'you r
language'). Type the program statements equivalent to the fo llowing pseudocode (you may
need to declare the va riable YourName first):
INPUT "What is your name? " YourName
OUTPUT "Have a nice day, "YourName
Save your program as Examplel and then run it. Is the output as you expected?
Cambridge International AS and A level Computer Science
A single alphanumeric CHAR Not available Char (2 bytes - char (1 byte -ASCI I)
character Unicode)
A sequence of STRING str (stored as ASCI I String (2 bytes per String (1 byte per
alphanumeric but Un icode strings character) character plus 1)
Use single ( 1 ) or double
characters (a string) are also available).
( ) quotation marks to
11 Use double (11 ) Use single ( 1 )
delimit a strin g. Use single ( 1 ), doub le quotation marks to quotation marks to
( ) or trip le (
11 111
or 111111 ) delimit a string. delimit a string.
quotation marks to
delimit a string.
Logical values: BOOLEAN bool Boolean (2 bytes) Boolean (1 byte)
True (represented as 1)
and
False (represented as 0)
See Chapter 1 (Sections 1.02 and 1.03) on how integers and characters are represented
inside the computer. Chapter 16 (Section 16.03) covers the internal representation of real
(sin gle, double, float) numbers.
The string data type is known as a structured type beca use it is essentially a sequence
of characters. A special case is the empty stri ng: a va lue of data type string, but w ith no
characters stored in it. In VB.N ET, each character in a string requires t wo bytes of memory
and each character is represented in memory as Unicode (in w hich, the va lu es from 1 to
127 correspond to ASCI I).
In Pascal, a string occup ies as many bytes as its maximum length plus one. The first byte
contains the current length of the string and the fol lowing bytes conta in the characters of the
string (stored as ASCII). Because the largest un signed integer that can be stored in a byte is
255, the ma ximum lengt h of a strin g is 255 characters.
Date and currency have va rious internal representations but are output in co nventional
format (except in Pascal w here you have to do a string conversion for dates).
f Chapter 13 Programming and Data Representation
r-
In Python, date and currency are not avai lable as built-i n dat a types . A date is stored as the
num ber of days after 1/1/0001, usi ng the datet ime cl ass (see Sect ion 13.08). For currency,
use f l oat.
VB.NET stores dates and tim es from 1.1.0001 (0 hours) to 31.1 2.9999 (23:59:59 hours) w ith a
reso luti on of 100 nan oseco nds (thi s unit is ca lled a 'ti ck'). Floatin g-point (d ecim al) numbers
are stored in binary-cod ed decim al fo rmat (see Sectio n 1.02). ·
There are many more data types . Programmers can also design and declare t heir own dat a
•
types (see Chapter 16 (Section 16.01) and Chapter 26 (Section 26 .02).
TASK13.02
1 Look at the identifier tab les in Cha pter 11 (Tables 11.02 and 11.04 to 11.12). Decide which
data type fro m your language is appropriate for each variable listed .
2 Write program code to implement the pseudocode from Worked Example 11.01 in Chapter 11.
Simpl e Bo olean exp ression s invo lve compariso n operators (Table 13.04). Co mplex Boolea n
exp ressions also invo lve Boo lea n o perators (Table 13.05).
13.05 Selection
IF. ..THEN statements
In pseu docode th e IF...THEN constr uct is wri tten as:
IF <Boolean expression>
THEN
<statement (s ) >
ENDIF
Syntax definitions
Python i f <Boolean expressio n >: Note t hat t he THEN keyword is replaced
<s tatement (s) > by a colon (:). Indent ation is used to
show w hich st atement s fo rm pa rt of th e
condi t ional stateme nt.
VB.NET If <Boolean e x pressio n > Then Note the pos ition of Then on the same
<statement (s ) > line as t he Boolean exp ress io n. The
End I f
End I f keywo rds should line up with
t he I f keyword .
Pascal if <Boolean expression> If more t ha n one st ateme nt is required
then as pa rt of the conditi onal state ment,
<Statement>;
the st atements must be put between
begin and end keywo rds.
Code examples
Pseudocode examp le:
IF x < 0
THEN
OUTPUT "Negativ e"
ENDIF
Python i f X < 0:
print ("Negative" )
Pascal if X < 0
then
WriteLn ( ' Ne gative ' ) ;
Chapter 13 Programming and Data Representation
TASK13.03
Write program code to implement the pseudocode from Worked Example ll.03 in Chapter ll.
Syntax definitions
Python if <Boolean expression>: Indentation· is used to show which
<statement (s) > statements form part of the
else :
conditiona l statement the else
<Statement (s) >
keyword must line up with the
co rresponding if keyword.
VB.NET If <Boolean expression> Then The Else keyword is on its own
<s tatement (s) > on a separate line. It is good
Else
programm ing practice to line it up
<statement (s) >
End I f
with the corresponding I f keyword
and indent the statements within
the conditiona l statement.
I
Pascal i f <Boolean expression> If more than one statement is
then
requ ired in the else part of the
<statement>
statement, the statements must be
else
placed between begin and end.
<Statement >;
Note the convention for indentation.
Code examples
Pseudocode examp le:
IF x < 0
THEN
OUTPUT "Negative"
ELSE
OUTPUT "Positive"
ENDIF
Cambridge International AS and A level Computer Science
Python if X < 0:
print ("Negative" )
else :
print ("Positive" )
VB.NET If X < 0 Then
Console . WriteLine ("Negat i ve ")
Else
Console . Wr i te Line ("Positive" )
End I f
Pascal if X < 0
the n
WriteLn( ' Negative ' )
el se
WriteLn( 'Positive');
Nested IF statements
In pseudocode, the nested IF statement is written as:
IF <Boo l ean expression>
THEN
<Statement (s) >
ELSE
IF <Boo l ean express i on>
THEN
<Statement (s) >
ELSE
<statement (s) >
ENDI F
ENDIF
Syntax definitions
Python if <Boolean expression>: Note the keyword elif (an
<statement (s) > abbreviation of e l se i f ). This
elif <Boolean expression>:
keyword must line up with the
<Statement (s) >
corresponding if.
else :
<Statement (s) > There can be as many elif parts
to this construct as required.
VB.NET If <Boo l ean express i on> Then If Else I f is used as one word,
<Statement (s) > only one End I f is required at the
Else I f
end of this construct.
<statement(s)>
Else There can be as many Elseif
<statement (s) > parts as requi red.
End I f
Pascal if <Boo l ean expression> Repeated indentation can make
then nested if statements quite
<Statement>
awkward . However, w ithout
e l se
careful indentation, the overview
if <Boolean expression>
can be lost. Whenever possible, a
t hen
<statement> CASE statement is preferable (see
e lse the next section).
<statement>;
- - - -~ - - - --- - ---- - - -- - -
)
\' Chapter 13 Programming and Data Representation
Code examples
Pseudocode example:
IF x < 0
THEN
OUTPUT "Negative"
ELSE
IF x = 0
THEN
OUTPUT "Zero"
ELSE
OUTPUT "Positive"
ENDIF
ENDIF
Python if X < 0:
print ("Negative" )
elif X = 0:
print ("Zero" )
else :
print ("Positive"}
VB.NET If x < 0 Then
Console .WriteLine(" Negative ")
Elseif x = O Then
Console . Wri teLine ( "Zero ")
Else
Pascal if
Console . WriteLine ( "Pos i tive ")
End I f
X < 0
I
then
Wri teLn ('Negative')
else
if X = 0
then
WriteLn(' Zero')
else
WriteLn( 'Positive');
TASK13.04
Write program code to implement the pseudocode from Worked Example 11.02 in Chapter 11.
~~~~~~~~~~~~~~~~~~~~~~~- - -
CASE statements
An alternative selection construct is t he CAS E statement. Each conside red CAS E condition
can be:
• a single value
• single values separated by commas
a ra nge.
In pse udocode, the CAS E statement is written as:
CASE OF <expre ss ion>
The value of <e x pression > determines w hich statement s are executed . There ca n be as many
separate cases as requ ired. The OTHERWISE clause is optional and useful for error trap pi ng.
Syntax definitions
Python Python does not have a CAS E stat ement. You need t o use nest ed If
stat ement s instead .
Case Else
<s t ateme n t (s ) >
End Select
Pascal case <expre ssion> of
v a l ue l : <stat ement >;
v alue2, v alue3 : <Statement >;
v alue4 . . v alue5 : <Statemen t >;
else
<statement >;
end ;
I
Code examples
In pseudocode, an example CAS E st at eme nt is:
CASE OF Grade
"An OUTPUT "Top grade "
11
F 11 , 11 U" OUTPUT "Fail"
11
B 11 •• 11 E 11 OUTPUT "Pa s s"
OTHERWISE
OUTPUT "Inv alid grade"
END CASE
r
Cambridge International AS and A level Computer Science
TASK13.05
The problem to be solved: the user enters the number of the month and year. The output
is the number of days in that month . The program has to check if the year is a leap year for
February.
The pseudocode solution is:
INPUT MonthNumber
INPUT Year
Days .... o
CASE OF MonthNumber
CASE 1,3,5,7,8,10,12: Days .... 31
CASE 4,6,9,11: Days <- 30
CASE 2: Days .... 28
If Year MOD 400 = 0
THEN II it is a leap year
Days .... 29
ENDIF
IF (Year MOD 4 = 0) AND (Year MOD 100 > 0)
THEN II it is a leap year
Days .... 29
ENDIF
OTHERWISE: OUTPUT "Invalid month number"
END CASE
OUTPUT Days
Write program code to implement the pseudocode above.
13.06 Iteration
Count-controlled (for) loops
In pseudocode, a count-controlled loop is written as:
FOR <control variable> .... s TO e STEP i II STEP is optional
<Statement (s) >
END FOR
The control variable starts with values, increments by value i each time round the loop and
finishes when the control variable reaches the value e.
Syntax definitions
Python for <Control variable> in range (s, e, i): The values s, e and i must
<Statement (s) > be of type integer.
The loop fin ishes when the
control variable is just below
e. The values for sand i can
be omitted and they default
too and 1, respectively.
VB.NET For <control variable> = s Toe Step i The values s, e and i can be
<statement (s) > of type integer or float.
Next
Pascal f or <control variable> .- s toe d o The control va riable can
<Statement>; be of type integer or char.
Intervals other than 1 are not
available.
Code examples
Python for x in range (5): The start value of xis Oand
print (x, end= ' ')
it increases by 1 on each
iteration.
Output: o 1 2 3 4
•
for x in range (2, 14, 3): Output: 2 5 8 11
print (x, end= ' ')
for x in range (5, 1, -1): The start value of xis 5 and
print (x , end=' ')
it decreases by 1 on each
iteration.
Output: 5 4 3 2
for x in ["ar• , r•b•• , "c" ]: The control variable takes
print (x, end= '' ) the value of each of the
group elements in turn.
Output: abc
VB.NET For x = 1 To 5 Output: 1 2 3 4 5
Console .Write (x)
Next
For x = 2 To 14 Step 3 Output: 2 5 8 11 1 4
Console .Wri te (x)
Next
For x = 5 To 1 Step -1 Output: 5 4 3 2 1
Console .Write (x)
Next
For x = 1 To 2.5 Step 0.5 Output:
Console .WriteLine(x)
1
Next
1. 5
2
2.5
Cambridge International AS and A level Computer Science
For Each x In { 11 a 11 , 11
h 11 , "c" } The control variable takes
Console .Write(x) t he value of each of the
Next
group elements in turn .
Output: abc
Pascal for x := 1 to 5 do Output: 1 2 3 4 s
write(x);
for x := 5 downto 1 do Output: s 4 3 2 1
write(x);
for x : = 'a' to 'c' do Output: abc
write (x ) ;
TASK13.06
1 Write program code to imp lement the pseudocode from Worked Example 11.05 in Chapter 11.
2 Write program code to implement the pseudocode from Worked Example 11.08 in Chapter 11.
3 Write program code to implement the pseudocode from Worked Example 11.09 in Chapter 11.
Post-condition loops
A post-condition loop, as the name suggests, executes the statements within the loop at
least once. When the condition is encountered, it is eva luated. As long as the condition
evaluates to False the statements within the loop are executed again. When the condition
evaluates to True, execution wi ll go to the next statement after the loop.
When coding a post-condition loop, you must ensure that there is a statement within the
loop that w ill at some point change the end condition to True. Otherwise the loop w ill
execute forever.
Syntax definitions
Python Post-cond ition loops are not available in Python. Use a
pre-condition loop instead.
VB.NET Do
<statement (s ) >
Loop Until <condition>
Pascal repeat
<statement(s)>;
until <condition>;
Code examples
Pseudocode example:
REPEAT
INPUT "Enter Y or N: "Answer
UNTIL Answer= "Y"
~ - -- -- - -- - - ~ -- - -- - -
',r
Chapter 13 Programming and Data Representation
r-
VB.NET Do
Console .Write ("Enter y or N: " )
Answer = Console . ReadLi ne ()
Loop Until Answer = 11y11
Pascal repeat
Write ( 'Enter y or N: ');
ReadLn(Answer);
until Answer = 'Y';
TASK13.07
1 Write program code to implement the pseudocode from Worked Example 11.04 in Chapter 11.
2 Write program code to implement the first algorithm from Worked Example 11.06 in
Chapter 11.
Pre-condition loops
Pre-condition loops, as the name suggest s, eva luate the condition before the statements
within the loop are executed. Pre-condition loops will execute the statements within the loop
as long as the condi t ion evaluates to True. When the condition evaluates to False, execu t ion
wil l go to the next statement afte r the loop. Note that any variable used in the condition must
not be undefined when the loop structure is first encountered.
When cod ing a pre-condition loop, you must ensure that there is a statement within the loop
that wil l at some point change the value of the controlling cond it ion. Otherwise the loop will
execute forever.
Syntax definitions
Python while <condi t i on>: Note that statements within the loop
<Statement (s) > must be indented by a set number of
spaces. The first statement after the loop
I
[ VB.NET Do While <condition> Note the keyword Loop indicates the end
<stateme n t (s) > of the loop.
Loop
Do Until <condition> VB.NET also has a pre-condition until
<statement (s) > loop. This will execute the statements
Loop within the loop as long as the condition
evaluates to False. If the condition
evaluates to True when the loop is first
encountered, the statements with in the
loop are not executed at all .
Pascal wh il e <Condition> do
<statement>;
Cambridge International AS and A level Computer Science
Code examples
Pseudocode example,
Answer ,e- " "
WHILE Answer<> "Y"
INPUT "Enter Y or N: "Answer
ENDWHILE
TASK13.08
Write program code to implement the second algorithm from Worked Example 11.06 in Chapter 11.
13.07 Arrays
Traditionally, an array is a static data st ructure. This means the array is declared w ith a
specified number of elements of one spec ified data type and this does not change after
compilation . Howeve r, many programming languages now allow an array to be dynamic. This
means the array can grow in size if required .
- - - - - - - - - -- - - - --
,-
f Chapter 13 Programming and Data Representation
r
Creating lD arrays
When we write a list on a piece of paper and number the individual item s, we wou ld normally
start the numbering with 1. You can view a 1D array like a numbered list of items. VB.NET
and Pyth o n number array elements from O (t he lower bound). Depending on the problem to
be solved, it might make sense to ignore element O. Pascal allows you to choose your lower
bound to be any integer. Th e upper bound is the largest number used for numbering the
elements of an array.
Syntax definitions
Python In Python, there are no arrays. The equ ivalent data stru ct ure is
called a li st. A list is an ordered sequence of items that do not have
to be of the same dat a type. Python's lists are dynamic.
VB.NET Dim <arrayidentifier > (< upperBound >) As <dataType >
var <arrayidentifier > : array [lowerBound .. upperBound]
Pascal of <dataTy pe >;
Code examples
Pseudocode example:
DECLARE Listl ARRAY[l:3] OF STRING II 3 elements in this list
•
DECLARE List2 ARRAY[0:5] OF INTEGER II 6 elements in this list
DECLARE List3 ARRAY[l:100) OF INTEGER II 100 elements in this list
DECLARE List4 ARRAY[0:25] OF STRING II 26 e l ements in this list
i
var List2 : array [10 .. 15] of integer;
integer ra nge or a char range.
var NList : array [l. .100] of integer;
Ranges can start with any value.
var AList : array[ 'A' .. ' Z'] of string;
.--- - - -
'
Cambridge International AS and A level Computer Science
Accessing lD arrays
A specific element in an array is accessed using an index va lue. In pseudocode, this is written as:
<arrayldentifier > [x)
Code examples
Pseudocode example:
NList[25) = O II set 25th element to zero
AList[3) = "D" II set 4th ele ment to let ter D
In Python, you can print the whole contents of a list using print(Li st). In VB.NET and
Pascal, you need to use a loop to print one element of an array at a time.
TASK13.09
l Write program code to implement the pseudocode from Worked Example 11.10 in Chapter 11.
2 Write program code to implement the pseudocode from Worked Example 11.11 in Chapter 11.
3 Write program code to implement the improved algorithm from Worked Example 11.12 in
Chapter 11.
Creating 2D arrays
When we write a t able of data (a matrix) on a piece of paper and want to refer to individual
elements of the table, t he convention is to give the row number first and then the column
number. When declaring a 2D array, the number of rows is given first, then the number of
co lum ns. Again we have lower and upper bounds for each dimension . VB .NET and Python
number all elements from 0.
In pseudocode, a 2D array declaration is written as:
DECLARE <identifier > : ARRAY [<lBoundl >: <uBo undl > ,
<1Bound2>:<u Bound2>) OF <dataType>
Syntax definitions
Python In Python , there are no arrays. The equ ivalent data structure is a
list of list s.
VB.NET Dim <a rray ldent ifier > (<uBoundl, uBound2 >) As
<dataType>
Pascal var <ar rayldentifier > : array [lBoundl.. uBoundl,
1Bound2 .. uBound2) of <dataType>;
Code examples
To declare a 2D array to rep resent a game board of six rows and seven colu mn s, th e
pseudocode statem ent is:
Board[l:6, 1:7) OF INTEGER
~ ---- -
•
char.
Accessing 2D arrays
A specific element in a table is accessed using an index pair. In pseudocode this is written as:
<a rrayidentifier > [x, y]
Code examples
Pseudocode examp le:
The following code examples demonstrate how to access elements in each of the three
languages.
•
I
TASK13.10
Write program code to implement the pseudocode from Worked Example 11.13; first in itialise
the table and then output its contents.
r
I
r
.--
I
- - -- -- -- ----
Cambridge International AS and A level Computer Science
Discussion Point:
Investigate your own programming environment and research other libra1·y routines .
characte r using Cou nts fro m 1 Counts from 0 Counts fro m 0 Count s from 1
its posit ion P in a
st ring
Return the CHAR( i ) c hr (i ) Chr(i) Ch r (i )
character
assoc iated with
the specified
character code
Return an ASC II (c h ) o r d(c h ) Asc(c h ) Ord (c h )
integer va lue
representing the
character code
of the specified
character
Return an integer LENGTH (S) l e n (S) l e n (S) L e n g th (S )
that contains
the nu mber of
cha racters in
string s
Return a su bstring LEFT (S , L) S[O: Ll Le f t(S, L) Uses t he StrUtils library
of lengt h L from See the next LeftStr (S , L )
Slicing in Python
In Python a subsequence of any sequence type (e.g. lists and strings) can be created using
'slicing'.
A slice is a substring of a string. For example, to get a substring of length L from position Pin
string S we write S[P: P + L].
ThisString
[OJ [l] [2] [3] [4] [5] [ 6]
A B C D E F G
If you imagine the numbering of each element to start at t he left-hand end (as shown in
Figure 13.05), t hen it is easier to see how the left element (the lower bound) is included, but
t he right element (the upper bound) is excluded . Tab le 13.07 shows some other usefu l slices
in Python.
~
includes al l charact ers to the end of the st ring.
ThisString [: 2] AB If you do not state the lower bound, the slice
~
includes all characters from t he beginning of
t he string.
r ThisString[-2:] FG A negative lower bound means that it takes the
~
slice starting from the end of the string.
ThisString (: -2] ABCDE A negative upper bound means that it
r
terminates the string at that position.
~ Table 13.07 Some useful slices in Python
Rounding numbers
So metimes we need to round numbers after a calculation involving real numbers. Rounding is
done away from zero. Th is means that 0.5 is rounded to 1 and - 0.5 is rounded to-1 .0.
Truncating numbers
Instead of rounding, sometimes we just want the w hole number part of a real number.
This is known as 'truncation'.
Sometimes a number with a decimal point may be held as a string. To use such a number in a
calculation, we first need to convert it to a real (float). Fo r example, these fu nctions return the
real number 75.43 from the string "75.43 ":
Python print (11 Nl: {0:>10} IN2: (1 :AlO } JN3 : {2:<10} I${ When using the placeho lder method for a
3:. 2f}" .format (Nl , N2, N3, Price) ) print st atement in Python , you can format
the output. Within{}, you give the number of
the ite m in the print list, then a colon(:) and
then these codes:
I\
centres the value
< align the va lue on the left
> aligns the value on the right
w a number giving the overall
character wi dth of the value
xf where xis the number of decimal
places for a floating point number
- - - --- - -
11
•
Randomize; This code initialises the random number
generator.
RandSeed .- <i nteger value> It can be useful, particularly during testing,
to produce the same sequence of random
numbers each time the program executes.
RandomRange (1, 6) There is a function in the Math library
that returns a random number between
two values, in this case 1 (inclusive) and 6
(exclusive).
TASK13.ll
l Write program code to generate 20 random numbers in the range l to 10 inclusive.
2 Write program code to implement the pseudocode using a pre-condition loop from
Worked Example 11.07 in Chapter 11.
TASK13.12
Write program code to get today's date from the system clock and output it with a suitable
message. Also output tomorrow's date with a suitable message. Will your program give the
correct information, regardless of which day it is executed?
Extend your program to output yesterday's date.
Discussion Point:
What other usefu l functions can you find? Which module libraries have you searched?
~
A text file consist s of a sequence of characters fo rmatted into lines. Each line is term inated by
an end-of-line marker. The text file is terminated by an end-of-file marker.
Note: you can check th e contents of a text file (or eve n create a text file re qu ired by a
program) by using a text editor suc h as NotePad.
The fo llow ing pseudocode statement s provide faci lities for writing t9 a fi le:
,
'
,
r
Cambridge International AS and A level Computer Science
Python FileHandle = ope n ("SampleFile.TXT" , "r11 ) You specify the filename and mode ('r' for
LineOfText = FileHandle .readline () read) when you call the open function .
FileHandle. close
VB.NET Dim LineOfText As String The file is accessed through an object (see
Dim FileHandle As System. Chapter 27) called a StreamReader.
IO. StreamReader
FileHandle = New System.
IO. StreamReader ( "Sampl eFi l e . TXT" )
LineOfText = FileHandle.ReadLine()
FileHandle .Close ()
Pascal var FileHandle : TextFile; The TextFile data type enables read
var LineOfText : String; access to a file. Note that the Reset
AssignFile(FileHandle, 'SampleFile. TXT');
procedu re opens the file fo r reading.
Reset (FileHandle);
ReadLn(FileHandle, LineOfText);
CloseFile (FileHandle);
Python FileHandle = o pen (" Samp l eF i le .TXT" , "a" ) You specify the filename and mode ('a' for
FileHandle.write(LineOfText) append) when you call the open function.
FileHandle. close ()
VB.NET Dim FileHandle As I O. StreamWriter The file is accessed through a
FileHandle = New StreamWriter. The extra parameter, True,
IO. StreamWriter (" SampleFi le . TXT" , True)
tells the system to append to the object.
FileHandle.WriteLine(LineOfText)
FileHandle. Close ()
Pascal var LineOfText : String; The TextFile data type enables append
var FileHandle : TextFile; access to a file. Note that the Append
AssignFile(FileHandle, 'SampleFile.TXT');
procedure opens the file for appending.
Append (FileHandle);
WriteLn(Fi leHandle, LineOfText);
CloseFile (FileHandle);
In pseudocode we call this function EOF(). We can use the construct REPEAT ... UNTIL EOF().
•
If it is possible that the fi le contains no data, it is better to use the construct WH ILE NOT
EOF()
t
!
For example, the followin g pseudocode statements read a text file and output its contents:
OPENFILE "Test . txt" FOR READ
WHILE NOT EOF("Test.txt")
READFILE "Test. txt", TextString
OUTPUT TextString
ENDWHILE
CLOSEFILE "Test. txt"
The following code examples demonstrate how to output the contents of a file in each of the
three languages.
rr
'
~-
I
r
Cambridge International AS and A level Computer Science
- - - - - - --
,-r- - - - - -
' '·
(' .
Chapter 13 Programming and Data Representation
Exam-style Questions
1 Matt wants a program to output a conversion table for ounces to grams (1 ounce is 28.35
grams). He w rites an algorithm:
Write program code to implement the algorithm . Include formatting, so that the output is tabulated. [7]
2 Write program code to accept an input string UserID. The program is to test the userID format. A valid format userID
consists of three upper case letters and four digits. The program is to output a message whether userrn is valid or not. [5]
3 Fred surveys the students at his college to find out their favou rite hobby. He wa nts to present
the data as a ta lly cha rt.
Fred plans to enter the data into the computer as he surveys the students. After data entry
is complete, he wants to output the total for each hobby.
a Write program code to declare and initialise t he array Tally[l:5) OF INTEGER. [5]
c Write program code to declare an array to store the hobby titles and rewrite the FOR loop of your program in
part (b) so that the hobby title is output before each tally. [4]
d Write program code to save the array data in a text file. [5]
e Write program code to read the data from the text file back into the initialised array. [5]