ALevel-CS Chapter 14
Programming and data representation
14.01 Programming languages
Python
Key characteristics:
- Every statement must be on a separate line.
- Indentation is significant. This is known as the ‘off-side rule’.
- Keywords are written in lower case.
- Python is case sensitive:: the identifier Number1 is seen as different from number1 or NUMBER1.
- Everything in Python is an object (see Chapter 27).
- Code makes extensive use of a concept called ‘slicing’ (see Section 14.07).
- Programs are interpreted (see Chapter 8, Section 8.05 for information on interpreted and compiled programs).
Java
Key characteristics:
- 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 (see Chapter 8, Section 8.05 for information on interpreted and compiled programs) into bytecode and then run using the Java Virtual Machine.
14.02 Programming basics
Key Terms
- Rules of precedence - define the order of the calculations to be performed
Declaration of variables
Pseudocode
DECLARE <identifier> : <dataType>
# Example
DECLARE Number1 : INTEGER // this declares Number1 to store a whole number
DECLARE YourName : STRING // this declares YourName to store a
// sequence of characters
DECLARE N1, N2, N3 : INTEGER // declares 3 integer variables
DECLARE Name1, Name2 : STRING // declares 2 string variables
Python
There are no declarations, but comments should be made at the beginning of a module
# Number1 of type Integer
# YourName of type String
# N1, N2, N3 of type integer;
# Name1, Name2 of type string;
Java
int number1;
String yourName;
int n1, n2, n3;
String name1, name2;
Declaration and assignment of constants
Pseudocode
CONSTANT <identifier> = <value>
# Example
CONSTANT Pi = 3.14
Python
PI = 3.14
Java
static final double PI = 3.14;
Assignment of Variables
Pseudocode
<identifier> ← <expression>
# Example
A ← 34
B ← B + 1
Python
# <identifier> = <expression>
A = 34
B = B + 1
Java
// <identifier> = <expression>;
A = 34;
B = B + 1;
Arithmetic operators
Operation | Pseudocode | Python | Java |
---|---|---|---|
Addition | + | + | + |
Substraction | - | - | - |
Multiplication | * | * | * |
Division | / | / | / |
Exponent | ^ | ** | No |
Integer division | DIV | // | / |
Modulus | MOD | % | % |
Outputting information to the screen
Pseudocode
OUTPUT <string>
OUTPUT <identifier(s)>
# Examples:
OUTPUT "Hello ", YourName, ". Your number is ", Number1 // newline
OUTPUT "Hello " // no new line
Python
# syntax
print(<printlist>)
print(<printlist>, end ='')
# Examples
print("Hello ", YourName, ". Your number is ", Number1)
print("Hello ", end= '')
print ("Hello {0}. Your number is {1}".format(YourName, Number1))
Java
// syntax
System.out.print(<printlist>);
System.out.println(<printlist>);
//Examples
System.out.println("Hello " + yourName + ". Your number is " + number1);
System.out.print("Hello");
Getting input from the user
Pseudocode
INPUT "Enter a number: " A
Python
A = input("Enter a number: ")
Java
import java.util.Scanner;
Scanner console = new Scanner(System.in);
System.out.print("Enter a number: ");
a = console.next();
Comments
Python
# this is a comment
# this is another comment
Java
// this is a comment
// this is another comment
/* this is a multi-line comment */
14.03 Data Types
Data Types
14.04 Boolean expressions
Boolean expressions
Comparision operators
14.05 Selection
Selection
Pseudocode
IF <Boolean expression>
THEN
<statement(s)>
ENDIF
IF <Boolean expression>
THEN
<statement(s)>
ELSE
<statement(s)>
ENDIF
# Examples
IF x < 0
THEN
OUTPUT "Negative"
ENDIF
IF x < 0
THEN
OUTPUT "Negative"
ELSE
OUTPUT "Positive"
ENDIF
Python
# Syntax
if <Boolean expression>:
<statement(s)>
if <Boolean expression>:
<statement(s)>
else:
<statement(s)>
# Examples
if x < 0:
print("Negative")
Java
// Syntax
if (<Boolean expression>)
<statement>;
if (<Boolean expression>)
<statement>;
else
<statement>;
// Examples
if (x < 0)
System.out.println("Negative");
if (x < 0)
System.out.println("Negative");
else
System.out.println("Positive");
Nested IF Statements
IF <Boolean expression>
THEN
<statement(s)>
ELSE
IF <Boolean expression>
THEN
<statement(s)>
ELSE
<statement(s)>
ENDIF
ENDIF
IF x < 0
THEN
OUTPUT "Negative"
ELSE
IF x = 0
THEN
OUTPUT "Zero"
ELSE
OUTPUT "Positive"
ENDIF
ENDIF
CASE statements
CASE condition:
- a single value
- single values separated by commas
- a range.
CASE OF <expression>
<value1> : <statement(s)>
<value2>,<value3> : <statement(s)>
<value4> TO <value5> : <statement(s)>
.
.
OTHERWISE <statement(s)>
ENDCASE
CASE OF Grade
"A" : OUTPUT "Top grade"
"F", "U" : OUTPUT "Fail"
"B".."E" : OUTPUT "Pass"
OTHERWISE OUTPUT "Invalid grade"
ENDCASE
Python
Python does not have a CASE statement. You need to use nested If statements instead.
Java
switch (<expression>)
{
case value1:
<statement(s)>;
break;
case value2: case value3:
<statement(s)>;
break;
.
.
.
default: <statement(s)>;
}
switch (grade) {
case 'A':
System.out.println("Top Grade");
break;
case 'F': case 'U':
System.out.println("Fail");
break;
case 'B': case 'C': case 'D': case 'E':
System.out.println("Pass");
break;
default:
System.out.println("Invalid grade");
}
14.06 Count-controller(FOR) loops
Count-controller(FOR) loops
Pseucocode
FOR <control variable> ← s TO e STEP i // STEP is optional
<statement(s)>
NEXT <control variable>
FOR x ← 1 TO 5
OUTPUT x
NEXT x
FOR x = 2 TO 14 STEP 3
OUTPUT x
NEXT x
FOR x = 5 TO 1 STEP -1
OUTPUT x
NEXT x
Python
for x in range(5):
print(x, end=' ')
for x in range(2, 14, 3):
print(x, end=' ')
for x in range(5, 1, -1):
print(x, end=' ')
for x in ["a", "b", "c"]:
print(x, end='')
java
for (int x = 1; x < 6; x++)
{
System.out.print(x);
}
for (int x = 2; x < 15; x = x + 3)
{
System.out.print(x + " ");
}
for (int x = 5; x > 0; x--)
{
System.out.print(x + " ");
}
for (double x = 1; x < 3; x = x + 0.5)
{
System.out.print(x + " ");
}
char[] letter = {'a', 'b', 'c'};
for (char x : letter )
{
System.out.print(x);
}
Post-condition loops
Pseudocode
REPEAT
<statement(s)>
UNTIL <condition>
example
REPEAT
INPUT "Enter Y or N: " Answer
UNTIL Answer = "Y"
Python
Post-condition loops are not available in Python. Use a pre-condition loop instead.
Java
do
{
<statement(s)>
} while <condition>;
//Examples
do
{
System.out.print("Enter Y or N: ");
answer = console.next();
} while (!(answer.equals("Y")));
Pre-condition loops
Pseudocode
WHILE <condition> DO
<statement(s)>
ENDWHILE
Answer ← ""
WHILE Answer <> "Y" DO
INPUT "Enter Y or N: " Answer
ENDWHILE
- 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.
Python
while <condition>:
<statement(s)>
# Examples
Answer = ''
while Answer != 'Y':
Answer = input("Enter Y or N: ")
Java
while (<condition>)
{
<statement(s)>;
}
//Examples
String answer = "";
while(answer.equals("Y") == false)
{
System.out.print("Enter Y or N: ");
answer = console.next();
}
14.07 Build-in functions
Build-in functions
Slicing in python
Truncating numbers
Pseudocode
INT(x : REAL) RETURNS INTEGER
STRING _ TO _ NUM(x : STRING) RETURNS REAL
Python
int(S)
float(x)
Java
Integer.valueOf(S)
Float.valueOf(x)
Random number generator
14.08 Procedure
Procddures
pseudocode
PROCEDURE <procedureIdentifier> // this is the procedure header
<statement(s)> // these statements are the procedure body
ENDPROCEDURE
CALL <procedureIdentifier>
# Examples
PROCEDURE InputOddNumber
REPEAT
INPUT "Enter an odd number: " Number
UNTIL Number MOD 2 = 1
OUTPUT "Valid number entered"
ENDPROCEDURE
CALL InputOddNumber
Syntax definitions
14.09 Functions
Functions
Pesudocode
FUNCTION <functionIdentifier> RETURNS <dataType> // function header
<statement(s)> // function body
RETURN <value>
ENDFUNCTION
# Examples
FUNCTION InputOddNumber RETURNS INTEGER
REPEAT
INPUT "Enter an odd number: " Number
UNTIL Number MOD 2 = 1
OUTPUT "Valid number entered"
RETURN Number
ENDFUNCTION
14.10 Passing parameters to subroutings
Key Terms
- Argument - the actual input expression or value with which the subroutine is being called
- Parameter - the variable(s) used inside a subroutine which will take values passed into a subroutine at call time
- Subroutine interface - the parameters being passed between the subroutine and the calling program
- Function / Procedure header - the first line of a function or procedure definition showing the identifier and parameter list
Passing parameters to subroutings
# function header
FUNCTION <functionIdentifier> (<parameterList>) RETURNS <dataType>
FUNCTION SumRange(FirstValue : INTEGER, LastValue : INTEGER) RETURNS INTEGER
DECLARE Sum, ThisValue : INTEGER
Sum ← 0
FOR ThisValue ← FirstValue TO LastValue
Sum ← Sum + ThisValue
NEXT ThisValue
RETURN Sum
ENDFUNCTION
14.12 Passing parameters to procedures
Key Terms
- By value - the actual value is passed into the procedure
- By reference - the address of the variable is passed into the procedure
Passing parameters to procedures
# procedure header
PROCEDURE <ProcedureIdentifier> (<parameterList>)
# parameter
BYREF <identifier1> : <dataType>
BYVALUE <identifier2> : <dataType>
Passing parametrs by value
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
Passing parameters by reference
PROCEDURE AdjustValuesForNextRow(BYREF Spaces : INTEGER, Symbols : INTEGER)
Spaces ← Spaces - 1
Symbols ← Symbols + 2
ENDPROCEDURE
CALL AdjustValuesForNextRow(NumberOfSpaces, NumberOfSymbols)
14.13 Putting it all together
14.14 Arrays
Arrays
pesudocode
DECLARE <arrayIdentifier> : ARRAY[<lowerBound>:<upperBound>] OF <dataType>
DECLARE List1 : ARRAY[1:3] OF STRING // 3 elements in this list
DECLARE List2 : ARRAY[0:5] OF INTEGER // 6 elements in this list
DECLARE List3 : ARRAY[1:100] OF INTEGER // 100 elements in this list
DECLARE List4 : ARRAY[0:25] OF STRING // 26 elements in this list
# accessing 1D arrays
<arrayIdentifier>[x]
# examples
NList[25] = 0 // set 25th element to zero AList[3] = "D" // set 3rd element to letter D
# creating 2D arrays
DECLARE <identifier> : ARRAY[<lBound1>:<uBound1>, <lBound2>:<uBound2>] OF <dataType>
# examples
DECLARE Board : ARRAY[1:6, 1:7] OF INTEGER
# accessing 2D arrays
<arrayIdentifier>[x, y]
# examples
Board[3,4] ← 0 // sets the element in row 3 and column 4 to zero
Python
List1 = []
List1.append("Fred")
List1.append("Jack")
List1.append("Ali")
List2 = [0, 0, 0, 0, 0, 0]
List3 = [0 for i in range(100)]
AList = [""] * 26
Board = [[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]]
Board = [[0 for i in range(7)] for j in range(6)]
Board = [[0] * 7] * 6
# accessing 2D array
Board[2][3] = 0
Java
String[] list1 = {"","",""};
int[] list2;
list2 = new int[5];
int[] list3;
list3 = new int[100];
String[] aList;
aList = new String[25];
int[][] board = { {0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0} }
int[][] board; board = new int[6][7];
//accessing 2D array
board[2][3] = 0;
14.15 Text files
Text files
# Writing to a text 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
# Reading from a text file
OPENFILE <filename> FOR READ // open file for reading
READFILE <filename>, <stringVariable> // read a line of text from the file
CLOSEFILE <filename> // close file
# Appending to a text file
OPENFILE <filename> FOR APPEND // open file for append
WRITEFILE <filename>, <stringValue> // write a line of text to the file
CLOSEFILE <filename> // close file
# The end-of-file (EOF) marker
OPENFILE "Test.txt" FOR READ
WHILE NOT EOF("Test.txt") DO
READFILE "Test.txt", TextString
OUTPUT TextString
ENDWHILE
CLOSEFILE "Test.txt"
python
# Writing to a text file
FileHandle = open("SampleFile.TXT", "w")
FileHandle.write(LineOfText)
FileHandle.close()
# Reading from a text file
FileHandle = open("SampleFile.TXT", "r")
LineOfText = FileHandle.readline()
FileHandle.close ()
# Appending to a text file
FileHandle = open("SampleFile.TXT", "a")
FileHandle.write(LineOfText)
FileHandle.close()
# The end-of-file (EOF) marker
FileHandle = open("Test.txt", "r")
LineOfText = FileHandle.readline()
while len(LineOfText) > 0:
LineOfText = FileHandle.readline()
print(LineOfText)
FileHandle.close()
Java
// Writing to a text file
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
FileWriter fileHandle = new FileWriter("SampleFile.TXT", false);
PrintWriter printLine = new PrintWriter(fileHandle);
String lineOfText;
printLine.printf("%s"+"%n", lineOfText);
printLine.close();
// Reading from a text file
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
FileReader fileHandle = new FileReader("SampleFile.TXT");
BufferedReader textReader = new BufferedReader(fileHandle);
String lineOfText = textReader.readLine();
textReader.close();
// Appending to a text file
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
FileWriter fileHandle = new FileWriter("SampleFile.TXT"), true);
PrintWriter printLine = new PrintWriter(fileHandle);
String lineOfText;
printLine.printf("%s"+"%n", lineOfText);
printLine.close();
// The end-of-file (EOF) marker
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
FileReader fileHandle = new FileReader("Test. txt");
BufferedReader textReader = new BufferedReader(fileHandle);
String lineOfText = textReader.readLine();
while (lineOfText != null)
{
System.out.println(lineOfText);
lineOfText = textReader.readLine();
}
textReader.close();