14.01-14.15 Programming and Data Representation
14.01-14.15 Programming and Data Representation
To write a computer program, we need to know the syntax (the correct structure of statements) of these basic
constructs in our chosen programming language.
Python - conceived by Guido van Rossum in the late 1980s. Python 2.0 was released in 2000 and Python 3.0 in
2008. Python is a multi-paradigm programming language, meaning that it fully supports both object-oriented
programming and structured programming. Many other paradigms, including logic programming, are supported
using extensions.
You can type a statement into the Python Shell and the Python interpreter will run it immediately (see Figure
14.01).
You can also type program code into a Python editor (such as IDLE), save it with a .py extension and then run the
program code from the Run menu in the editor window (see Figure 14.02).
Figure 14.02 (a) A saved program in the Python editor window and (b) running in the Python shell
Visual Basic Console Mode (VB.NET) - a multi-paradigm, high-level programming language, implemented on the
.NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Visual Basic language.
Microsoft’s integrated development environment (IDE) for developing in VB.NET is Visual Studio. Visual Studio
Express and Visual Studio Community are freeware.
You type your program code into the Integrated Development Environment (IDE) as shown in Figure 14.03 (a),
save the program code and then click on the Run button . This starts the compiler. If there are no syntax errors
the compiled program will then run. Output will be shown in a separate console window (see Figure 14.03 (b)).
Note that the console window shuts when the program has finished execution. To keep the console window open
so you can see the output (see Figure 14.03), the last statement of your program should be
Console.ReadLine()
Figure 14.03 (a) A saved program in the VB.NET editor and (b) running in the program execution (console) window
Java - originally developed by James Gosling at Sun Microsystems (now owned by Oracle) and released in 1995.
The Java Runtime Environment (JRE) is intended for end users, and the Java Development Kit (JDK) is intended
for software developers and includes development tools such as the Java compiler and a debugger.
Java was intended to be platform independent. The Java programs in this book have been prepared using
NetBeans 8.2. However, any text editor can be used to write Java source code.
- Every statement ends with a semicolon (;). More than one statement can go on a single line, but this is not
recommended.
- Indentation is good practice. Java is case sensitive.
- The convention is to use camelCaps for identifiers, lower case for keywords and capitalised identifiers for
classes.
- A compound statement consists of a sequence of statements enclosed between braces { }. Whenever Java
syntax requires a statement, a compound statement can be used.
- Programs need to be compiled into bytecode and then run using the Java Virtual Machine.
Java was designed almost exclusively as an object-oriented language. All code is written inside classes. Only the
simple data types (such as integer, real) are not objects. Strings are objects.
Source files must be named after the public class they contain, appending the suffix .java, for example, Ex1.java. It
must first be compiled into bytecode, using a Java compiler, producing a file named Ex1.class. Only then can it be
executed.
The method name “main” is not a keyword in the Java language. It is simply the name of the method the Java
launcher calls to pass control to the program. You type your program statements into the Integrated Development
Environment (IDE) as shown in Figure 14.04, save the program code and then click on the Run button ( ). This
starts the compiler. If there are no syntax errors the compiled program code will then run. Output will be shown in
the Output window (see Figure 14.04).
Programming basics
Declaration of variables - Most programming languages require you to declare the type of data to be stored in a
variable, so the correct amount of memory space can be reserved by the compiler. A variable declared to store a
whole number (integer) cannot then be used to store alphanumeric characters (strings), or the other way around.
VB.NET and Java require variables to be declared before they are used.
Python handles variables differently to most programming languages. It tags values. This is why Python does not
have variable declarations.
Code examples
Declaration and assignment of constants - Sometimes we use a value in a solution that never changes, for
example, the value of the mathematical constant pi (π). Instead of using the actual value in program statements, it
is good practice and helps readability, if we give a constant value a name and declare it at the beginning of the
program.
Syntax definitions
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
In the examples below, the print list consists of four separate items:
“Hello ” and “. Your number is ” are strings and
YourName and Number1 are variables, for which we print the value.
In pseudocode, we can indicate whether a new line should be output at the end by a comment at the end of the
statement.
OUTPUT "Hello ", YourName, ". Your number is ", Number1 // newline OUTPUT "Hello " // no new line
In Python and VB.NET you can also use the placeholder method for output: the variables to be printed are
represented by sequential numbers in { } in the message string and the variables are listed in the correct order after
the string, separated by commas:
Getting input from the user - When coding an input statement, it is good practice to prompt the user as to what
they are meant to enter. For example, consider the pseudocode statement:
INPUT "Enter a number: " A
Note the space between the colon and the closing quote. This is significant. It gives a space before the user types
their input.
Data types
Every programming language has built-in data types. Table 14.02 gives a subset of those available. The number of
bytes of memory allocated to a variable of the given type is given in brackets for VB.NET and Java.
Boolean expressions
Simple Boolean expressions involve comparison operators. Complex Boolean expressions also involve Boolean
operators.
Selection
IF...THEN statements
In pseudocode the IF...THEN construct is written as:
IF <Boolean expression>
THEN
<statement(s)>
ENDIF
Syntax definitions
IF...THEN...ELSE statements
In pseudocode, the IF...THEN...ELSE construct is written as:
IF <Boolean expression>
THEN
<statement(s)>
ELSE
<statement(s)>
ENDIF
An alternative selection construct is the CASE statement. Each considered CASE condition can be:
a single value
single values separated by commas a range.
In pseudocode, the CASE statement is written as:
CASE OF <expression>
<value1> : <statement(s)> <value2>,<value3> : <statement(s)> <value4> TO <value5> : <statement(s)> ..
OTHERWISE <statement(s)>
ENDCASE
The value of <expression> determines which statements are executed. There can be as many separate
cases as required. The OTHERWISE clause is optional and useful for error trapping.
Iteration
Count-controlled (FOR) loops
In pseudocode, a count-controlled loop is written as:
FOR <control variable> ← s TO e STEP i // STEP is optional <statement(s)>
NEXT <control variable>
The control variable starts with value s, increments by value i each time round the loop and finishes when the
control variable reaches the value e.
Syntax definitions
Post-condition loops - executes the statements within the loop at least once. When the condition is encountered,
it is evaluated. As long as the condition evaluates to False, the statements within the loop are executed again.
When the condition evaluates to True, execution will 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 will at some point
change the end condition to True. Otherwise the loop will execute forever.
In pseudocode, the post-condition loop is written as:
REPEAT
<statement(s)>
UNTIL <condition>
Syntax definitions
Which loop structure to use? If you know how many times around the loop you need to go when the program
execution gets to the loop statements, use a count-controlled loop. If the termination of the loop depends on some
condition determined by what happens within the loop, then use a conditional loop. A pre-condition loop has the
added benefit that the loop may not be entered at all, if the condition does not require it.
Built-in functions
Programming environments provide many built-in functions. Some of them are always available to use; some need
to be imported from specialist module libraries.
For example, to get a substring of length L from position P in string S we write S[P : P + L].
Figure 13.05 shows a representation of ThisString. If we want to return a slice of length 3 starting at position 3, we
use ThisString[3 : 6] to give ‘DEF’. Position is counted from 0 and the position at the upper bound of the slice is not
included in the substring.
If you imagine the numbering of each element to start at the left-hand end, then it is easier to see how the left
element (the lower bound) is included, but the right element (the upper bound) is excluded.
Procedures
In pseudocode, a procedure definition is written as:
PROCEDURE <procedureIdentifier> // this is the procedure header <statement(s)> // these statements are the
procedure body
ENDPROCEDURE
This procedure is called using the pseudocode statement:
CALL <procedureIdentifier>
Syntax definitions
When programming a procedure, note where the definition is written and how the procedure is called from the main
program.
Here is an example pseudocode procedure definition:
PROCEDURE InputOddNumber REPEAT
INPUT "Enter an odd number: " Number UNTIL Number MOD 2 = 1
OUTPUT "Valid number entered"
ENDPROCEDURE
This procedure is called using the CALL statement:
CALL InputOddNumber
Code examples
Functions
You can write your own functions. Any function you have written can be used in another program if you build up
your own module library.
A function is used as part of an expression. When program execution gets to the statement that includes a function
call as part of the expression, the function is executed. The return value from this function call is then used in the
expression. When writing your own function, ensure you always return a value as part of the statements that make
up the function (the function body). You can have more than one RETURN statement if there are different paths
through the function body.
Syntax definitions
Code examples
Passing parameters to procedures
If a parameter is passed by value, at call time the argument can be an actual value (as we showed in the code. If
the argument is a variable, then a copy of the current value of the variable is passed into the subroutine. The value
of the variable in the calling program is not affected by what happens in the subroutine.
For procedures, a parameter can be passed by reference. At call time, the argument must be a variable. A pointer
to the memory location (the address) of that variable is passed into the procedure. Any changes that are applied to
the variable’s contents will be effective outside the procedure in the calling program/module.
Note that neither of these methods of parameter passing applies to Python. In Python or Java, the method is called
pass by object reference. This is basically an object-oriented way of passing parameters and is beyond the scope
of this chapter. The important point is to understand how to program in Python and Java to get the desired effect.
The full procedure header is written in pseudocode, in a very similar fashion to that for function headers, as:
The parameter list needs more information for a procedure definition. In pseudocode, a parameter in the list is
represented in one of the following formats:
BYREF <identifier1> : <dataType>
BYVALUE <identifier2> : <dataType>
Passing parameters by value - The pseudocode for the pyramid example in Chapter 12 includes a procedure
definition that uses two parameters passed by value. We can now make that explicit:
PROCEDURE OutputSymbols(BYVALUE NumberOfSymbols : INTEGER, Symbol : CHAR) DECLARE Count :
INTEGER
FOR Count ← 1 TO NumberOfSymbols
OUTPUT Symbol // without moving to next line NEXT Count
OUTPUT NewLine
ENDPROCEDURE
In Python, all parameters behave like local variables and their effect is as though they are passed by value.
Passing parameters by reference - When parameters are passed by reference, when the values inside the
subroutine change, this affects the values of the variables in the calling program.
Consider the pseudocode procedure AdjustValuesForNextRow below.
The pseudocode for the pyramid example generated in Chapter 12 includes a procedure definition that uses two
parameters passed by reference. We can now make that explicit:
PROCEDURE AdjustValuesForNextRow(BYREF Spaces : INTEGER, Symbols : INTEGER) Spaces ← Spaces - 1
Symbols ← Symbols + 2
ENDPROCEDURE
The pseudocode statement to call the procedure is:
CALL AdjustValuesForNextRow(NumberOfSpaces, NumberOfSymbols)
The values of the parameters Spaces and Symbols are changed within the procedure when this is called. The
variables NumberOfSpaces and NumberOfSymbols in the program code after the call will store the updated values
that were passed back from the procedure.
Python does not have a facility to pass parameters by reference. Instead the subroutine behaves as a
function and returns multiple values. Note the order of the variables as they receive these values in the main part of
the program.
Arrays
Creating 1D arrays
VB.NET, Python and Java number array elements from 0 (the lower bound). In pseudocode, a 1D array declaration
is written as:
Syntax definitions
Accessing 1D arrays
A specific element in an array is accessed using an index value. In pseudocode, this is written as:
<arrayIdentifier>[x]
Pseudocode example:
Text files
Writing to a text file - The following pseudocode statements provide facilities for writing to a file:
OPENFILE <filename> FOR WRITE // open the file for writing
WRITEFILE <filename>, <stringValue> // write a line of text to the file
CLOSEFILE <filename> // close file
The following code examples demonstrate how to open, write to and close a file called SampleFile.TXT in each of
the three languages. If the file already exists, it is overwritten as soon as the file handle is assigned by the ‘open
file’ command.
Code examples
Reading from a text file - An existing file can be read by a program. The following pseudocode statements provide
facilities for reading from a file:
The following code examples demonstrate how to open, read from and close a file called SampleFile.TXT in each
of the three languages.