0% found this document useful (0 votes)
13 views

CHP 8 Programming MS

Uploaded by

momina.abrar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

CHP 8 Programming MS

Uploaded by

momina.abrar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Answers to Algorithms, Programming and Logic Workbook

16 a OUTPUT T should be INPUT T


T < 30 should be T < 20
No flowline out of the OUTPUT "Too Low" box.
T > 20 should be T > 30
Flowlines from the decision box are not labelled.
The arrow on the horizontal flowline is at the wrong end and points in the wrong direction.
No flowline out of the OUTPUT "Too High" box.
b

8 Programming
1 Three from:
x integer: a positive or negative whole number that can be used with mathematical operators
x real: a positive or negative number with a fractional part that can be used with
mathematical operators
x Boolean: a variable or constant that can have only two values TRUE or FALSE
x char: a single alphanumeric character
x string: multiple alphanumeric characters

Cambridge IGCSE and O Level Computer Science Teacher's Guide 14


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

2 a Python
Number1 = int(input("Please enter the first whole number "))
Number2 = int(input("Please enter the second whole number "))
Number3 = int(input("Please enter the third whole number "))
Visual Basic
Console.Write("Please enter first whole number ")
Number1 = Integer.Parse(Console.ReadLine())
Console.Write("Please enter second whole number ")
Number2 = Integer.Parse(Console.ReadLine())
Console.Write("Please enter third whole number ")
Number3 = Integer.Parse(Console.ReadLine())
Java
System.out.print("Please enter the first whole number ");
Number1 = myObj.nextInt();
System.out.print("Please enter the second whole number ");
Number2 = myObj.nextInt();
System.out.print("Please enter the third whole number ");
Number3 = myObj.nextInt();
b Python
Number1 = 10
Number2 = 20
Number3 = 30
Visual Basic
Number1 = 10
Number2 = 20
Number3 = 30
Java
Number1 = 10;
Number2 = 20;
Number3 = 30;
c Python
print("Integer values assigned and stored", Number1, Number2,
Number3)
Visual Basic
Console.WriteLine("Integer values assigned and stored " &
Number1 & " " & Number2 & " " & Number3)
Java
System.out.println("Integer values assigned and stored " +
Number1 + " " + Number2 + " " + Number3);

Cambridge IGCSE and O Level Computer Science Teacher's Guide 15


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

d Python
Number1 = int(input("Please enter the first whole number "))
Number2 = int(input("Please enter the second whole number "))
Number3 = int(input("Please enter the third whole number "))

print("Integer values entered", Number1, Number2, Number3)

Number1 = 10
Number2 = 20
Number3 = 30

print("Integer values assigned and stored" , Number1,


Number2, Number3)

Visual Basic
Module Module1

Sub Main()
Dim Number1, Number2, Number3 As Integer
Console.Write("Please enter first whole number ")
Number1 = Integer.Parse(Console.ReadLine())
Console.Write("Please enter second whole number ")
Number2 = Integer.Parse(Console.ReadLine())
Console.Write("Please enter third whole number ")
Number3 = Integer.Parse(Console.ReadLine())

Console.WriteLine("Integer values entered " & Number1


& " " & Number2 & " " & Number3)

Number1 = 10
Number2 = 20
Number3 = 30

Console.WriteLine("Integer values assigned and stored


" & Number1 & " " & Number2 & " " & Number3)

Console.ReadKey()
End Sub

End Module

Cambridge IGCSE and O Level Computer Science Teacher's Guide 16


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Java
import java.util.Scanner;
class Q2 Java
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);

int Number1, Number2, Number3;

System.out.print("Please enter the first whole number ");


Number1 = myObj.nextInt();
System.out.print("Please enter the second whole number ");
Number2 = myObj.nextInt();
System.out.print("Please enter the third whole number ");
Number3 = myObj.nextInt();

System.out.println("Integer values entered " +


Number1 + " " + Number2 +" " + Number3);

Number1 = 10;
Number2 = 20;
Number3 = 30;

System.out.println("Integer values assigned and


stored" + Number1 + " " + Number2 + " " + Number3);
}
}
3 a Python
weight = 0
while weight < 0.5 or weight > 5.0:
weight = float(input("Please enter the weight of your
parcel "))
Visual Basic
weight = 0
While (weight < 0.5) Or (weight > 5.0)
Console.Write("Please enter the weight of your parcel ")
weight = Decimal.Parse(Console.ReadLine())
End While

Cambridge IGCSE and O Level Computer Science Teacher's Guide 17


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Java
do {
System.out.print("Please enter the weight of your parcel ");
weight = myObj.nextDouble();
}
while (weight < 0.5 || weight > 5.0);
b Python
print(" Options")
print(" 1 Guaranteed next day delivery before noon")
print(" 2 Guaranteed next day delivery")
print(" 3 24-hour delivery")
print(" 4 48-hour delivery")
print(" 5 3-5 days delivery")
option = int(input("Please enter your chosen option "))

if option == 1:
# option 1 code
elif option == 2:
# option 2 code
elif option == 3:
# option 3 code
elif option == 4:
# option 4 code
elif option == 5:
# option 5 code
else:
print("Incorrect option chosen")

Visual Basic
Console.WriteLine(" Options")
Console.WriteLine(" 1 Guaranteed next day delivery before
noon")
Console.WriteLine(" 2 Guaranteed next day delivery")
Console.WriteLine(" 3 24-hour delivery")
Console.WriteLine(" 4 48-hour delivery")
Console.WriteLine(" 5 3-5 days delivery")

Console.Write ("Please enter your chosen option ")


opt = Integer.Parse(Console.ReadLine())

Cambridge IGCSE and O Level Computer Science Teacher's Guide 18


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Select Case opt


Case 1
'option 1 code
Case 2
'option 2 code
Case 3
'option 3 code
Case 4
'option 4 code
Case 5
'option 5 code
Case Else
Console.WriteLine("Incorrect option chosen")
End Select
Java
System.out.println(" Options");
System.out.println(" 1 Guaranteed next day delivery before
noon");
System.out.println(" 2 Guaranteed next day delivery");
System.out.println(" 3 24-hour delivery");
System.out.println(" 4 48-hour delivery");
System.out.println(" 5 3-5 days delivery");

System.out.print("Please enter your chosen option ");


option = myObj.nextInt();
switch (option) {
case 1:
//option 1 code ;
break;
case 2:
//option 2 code;
break;
case 3:
//option 3 code;
break;
case 4:
//option 4 code;
break;

Cambridge IGCSE and O Level Computer Science Teacher's Guide 19


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

case 5:
//option 5 code;
break;
default:
System.out.println("Incorrect option chosen");
}
c Python
weight = 0
while weight < 0.5 or weight > 5.0:
weight = float(input("Please enter the weight of your
parcel "))

print(" Options")
print(" 1 Guaranteed next day delivery before noon")
print(" 2 Guaranteed next day delivery")
print(" 3 24-hour delivery")
print(" 4 48-hour delivery")
print(" 5 3-5 days delivery")
option = int(input("Please enter your chosen option "))

if option == 1:
cost = weight * 10 + 1
elif option == 2:
cost = weight * 10
elif option == 3:
cost = 5
elif option == 4:
cost = 4
elif option == 5:
cost = 3
else:
print ("Incorrect option chosen")
cost = 0

print ("Your cost is ", cost)

Cambridge IGCSE and O Level Computer Science Teacher's Guide 20


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Visual Basic
Module Module1

Sub Main()
Dim weight, cost As Decimal
Dim opt As Integer
weight = 0
While (weight < 0.5) Or (weight > 5.0)
Console.Write("Please enter the weight of your
parcel ")
weight = Decimal.Parse(Console.ReadLine())
End While

Console.WriteLine(" Options")
Console.WriteLine(" 1 Guaranteed next day delivery
before noon")
Console.WriteLine(" 2 Guaranteed next day delivery")
Console.WriteLine(" 3 24-hour delivery")
Console.WriteLine(" 4 48-hour delivery")
Console.WriteLine(" 5 3-5 days delivery")

Console.Write("Please enter your chosen option ")


opt = Integer.Parse(Console.ReadLine())

Select Case opt


Case 1
cost = weight * 10 + 1
Case 2
cost = weight * 10
Case 3
cost = 5
Case 4
cost = 4
Case 5
cost = 3
Case Else
Console.WriteLine("Incorrect option chosen")
cost = 0
End Select

Cambridge IGCSE and O Level Computer Science Teacher's Guide 21


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Console.WriteLine("Your cost is " & cost)

Console.ReadKey()

End Sub

End Module
Java
import java.util.Scanner;
class Q3Java
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
double weight, cost;
int option;

do {
System.out.print("Please enter the weight of your
parcel ");
weight = myObj.nextDouble();
}
while (weight < 0.5 || weight > 5.0);

System.out.println(" Options");
System.out.println(" 1 Guaranteed next day delivery
before noon");
System.out.println(" 2 Guaranteed next day delivery");
System.out.println(" 3 24-hour delivery");
System.out.println(" 4 48-hour delivery");
System.out.println(" 5 3-5 days delivery");

System.out.print("Please enter your chosen option ");


option = myObj.nextInt();
switch (option) {
case 1:
cost = weight * 10 + 1;
break;

Cambridge IGCSE and O Level Computer Science Teacher's Guide 22


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

case 2:
cost = weight * 10;
break;
case 3:
cost = 5;
break;
case 4:
cost = 4;
break;
case 5:
cost = 3;
break;
default:
System.out.println("Incorrect option chosen");
cost = 0;
}
System.out.println("Your cost is " + cost);
}
}
d Test data Expected output Actual output
0.4 Error message
 Error message
í1 Error message
2SWLRQ Your cost is 6
2SWLRQ <RXUFRVWLV
2SWLRQ <RXUFRVWLV
2SWLRQ <RXUFRVWLV
2SWLRQ <RXUFRVWLV
2SWLRQ Your cost is 4
2SWLRQ Your cost is 3
1 Option 7 Incorrect option chosen

Cambridge IGCSE and O Level Computer Science Teacher's Guide 23


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

4 a Counting: keeping a count of the number of times an action is performed:


Counter = Counter + 1
b Iteration: a section of programming code can be repeated under certain conditions.
For example, a pre-condition loop:
Python
while TotalWeight < 100:
TotalWeight = TotalWeight + Weight
Visual Basic
While TotalWeight < 100
TotalWeight = TotalWeight + Weight
End While
Java
while (TotalWeight < 100)
{
TotalWeight = TotalWeight + Weight;
}
c Selection: allowing the selection of different paths through the steps of a program:
Python
if Age > 17:
print("You are an adult")
Visual Basic
If Age > 17 Then
Console.WriteLine("You are an adult")
End If
Java
if (Age > 17) {
System.out.println ("You are an adult");
}
d Sequence – the order that steps in a program are executed.
For example: TotalWeight and Weight must be assigned values before the WHILE
loop is executed.
Python
TotalWeight = 0
while TotalWeight < 100:
Weight = float(input("Enter the next weight: "))
TotalWeight = TotalWeight + Weight

Cambridge IGCSE and O Level Computer Science Teacher's Guide 24


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Visual Basic
Dim Weight, TotalWeight As Decimal
TotalWeight = 0

While TotalWeight < 100


Console.WriteLine("Please enter the weight of your parcel ")
Weight = Decimal.Parse(Console.ReadLine())
TotalWeight = TotalWeight + Weight
End While
Java
import java.util.Scanner;
class Q4{
public static void main(String args[])
{
double TotalWeight = 0;
double Weight;
Scanner myObj = new Scanner(System.in);

while (TotalWeight < 100)


{
System.out.print("Please enter the weight of
your parcel ");
Weight = myObj.nextDouble();
TotalWeight = TotalWeight + Weight;
}
}
}
e String handling – strings are used to store text. Every string contains a number of
characters, from an empty string which has no characters stored to a maximum number
specified by the programming language. The characters in a string can be labelled by
position number. The first character in a string can be in position zero or position one,
depending on the language.
For example, finding the number of characters in a string:
Python
len(MyString)
Visual Basic
MyString.Length()
Java
MyString.length();

Cambridge IGCSE and O Level Computer Science Teacher's Guide 25


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

5 // Algorithm to input ten positive numbers and total them,


// output the total and then average
DECLARE A, B, C, D : INTEGER
DECLARE D : REAL
A m 0
B m 0

REPEAT
REPEAT
OUTPUT "Please enter a positive number "
INPUT C
UNTIL C > 0
A m A + C
B m B + 1
UNTIL B = 10
D m A / B
OUTPUT A, D
6 a Python
# Python program to total 10 numbers and find the average
Total = 0
Counter = 0 # Total and Counter initialised to zero

while Counter < 10:


Number = int(input("Please enter a positive number "))
while Number <= 0: # error trapping for negative numbers
Number = int(input("Your number was zero or negative, please try
again"))
Total = Total + Number
Counter = Counter + 1 # updating Total and Counter

Average = Total / Counter # calculating the Average

print(" The total is ", Total, " the average is ", Average)
# outputting the results

Cambridge IGCSE and O Level Computer Science Teacher's Guide 26


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Visual Basic
'Visual Basic program to total 10 numbers and find the average

Module Module1

Sub Main()
Dim Total, Number, Counter As Integer
Dim Average As Decimal ' variables declared

Total = 0
Counter = 0 ' Total and Counter initialised To zero

Do
Console.Write("Please enter a positive number ")
Number = Int(Console.ReadLine())

While (Number <= 0) 'error trapping for negative numbers


Console.Write("Your number was zero or negative. Please try
again ")
Number = Int(Console.ReadLine())
End While

Total = Total + Number


Counter = Counter + 1 'updating Total And Counter
Loop Until Counter = 10

Average = Total / Counter ' calculating the Average

Console.WriteLine(" The total is " & Total & " the average is " &
Average) ' outputting the results

Console.ReadLine()

End Sub

End Module

Cambridge IGCSE and O Level Computer Science Teacher's Guide 27


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Java
// Java program to total 10 numbers and find the average
import java.util.Scanner;
class Q6Java
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);

int Counter, Number;


double Average Total; //variables declared , Total must be double
otherwise the division will be truncated

Total = 0;
Counter = 0; //Total and Counter initialised To zero

do {

System.out.print("Please enter a positive number ");


Number = myObj.nextInt();

while (Number <= 0){

System.out.print("Your number was zero or negative. Please


try again ");
Number = myObj.nextInt(); //error trapping for negative
numbers
}

Total = Total + Number;


Counter = Counter + 1; //updating Total And Counter
}
while (Counter < 10);

Average = Total / Counter ; // calculating the Average

System.out.println(" The total is " + Total + " the average is " +


Average);//outputting the results
}
}

Cambridge IGCSE and O Level Computer Science Teacher's Guide 28


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

b Total Number Counter Average OUTPUT


0 0
4 4 1 Please enter a positive number
7 3 2 Please enter a positive number
14 7 3 Please enter a positive number
20 6 4 Please enter a positive number
Your number was negative or
0
zero, please try again
Your number was negative or
-3
zero, please try again
29 9 5 Please enter a positive number
30 1 6 Please enter a positive number
38 8 7 Please enter a positive number
43 5 8 Please enter a positive number
45 2 9 Please enter a positive number
50 5 10 Please enter a positive number
The total is 50 the average
5.0
is 5.0

7 a Python
Student = ["Alice", "Jan", "Lim", "Ian", "Min", "Sue", "Tim",
"Dee"]
for Counter in range(8):
print(Student[Counter])
print()

Counter = 0
while Counter < 8:
print(Student[Counter])
Counter = Counter + 1
print()
Visual Basic
For Counter = 0 To 7
Console.WriteLine(Student(Counter))
Next
Console.WriteLine()

Cambridge IGCSE and O Level Computer Science Teacher's Guide 29


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Counter = 0
Do
Console.WriteLine(Student(Counter))
Counter = Counter + 1
Loop Until Counter = 8

Console.WriteLine()
Java
for (Counter = 0; Counter <= 7; Counter++) {
System.out.println(Student[Counter]);
}
System.out.println()

Counter = 0;
while (Counter <= 7){
System.out.println(Student[Counter]);
Counter++;
}
System.out.println()
b Python
NumberOfStudents = len(Student)

Counter = 0
while Counter < NumberOfStudents:
print(Student[Counter])
Counter = Counter + 1
print("Number of students", NumberOfStudents)
Visual Basic
NumberOfStudents = Student.Length
Counter = 0
Do
Console.WriteLine(Student(Counter))
Counter = Counter + 1
Loop Until Counter = NumberOfStudents

Console.WriteLine("Number of students " & NumberOfStudents)


Java
NumberOfStudents = Student.length;
Counter = 0;
while (Counter < NumberOfStudents){
System.out.println("Number of students " + NumberOfStudents);
Counter++;
}
8 a Find the length: LENGTH(MyString)
Convert to upper case: UCASE(MyString)
Convert to lower case: LCASE(MyString)
Find the first character: SUBSTRING(MyString, 1, 1)

Cambridge IGCSE and O Level Computer Science Teacher's Guide 30


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

b Python
MyString = "Test String"
Length = len(MyString)
FirstChar = MyString[0:1]
UpperCase = MyString.upper()
LowerCase = MyString.lower()

print("Length of string ", Length)


print("First character of string ", FirstChar)
print("String in upper case ", UpperCase)
print("String in lower case ", LowerCase)
Visual Basic
Module Module1
Sub Main()
Dim MyString, FirstChar, UpperCase, LowerCase As String
Dim Length As Integer
MyString = "Test String"
Length = MyString.Length()
FirstChar = MyString.Substring(0, 1)
UpperCase = UCase(MyString)
LowerCase = LCase(MyString)
Console.WriteLine("Length of string " & Length)
Console.WriteLine("First character of string " & FirstChar)
Console.WriteLine("String in upper case " & UpperCase)
Console.WriteLine("String in lower case " & LowerCase)
Console.ReadKey()
End Sub
End Module
Java
import java.util.*;
class Q8Java
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);

String MyString, FirstChar, UpperCase, LowerCase;


int Length;
MyString = "Test String";
Length = MyString.length();
FirstChar = MyString.substring(0, 1);
UpperCase = MyString.toUpperCase();
LowerCase = MyString.toLowerCase();
System.out.println("Length of string " + Length);
System.out.println("First character of string " +
FirstChar);
System.out.println("String in upper case " + UpperCase);
System.out.println("String in lower case " + LowerCase);
}
}

Cambridge IGCSE and O Level Computer Science Teacher's Guide 31


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

9 a Python
A = ((B + C – D * E) ** F) / G
Visual Basic
A = ((B + C – D * E) ^ F) / G
Java
A = Math.pow((B + C – D * E), F) / G;
b Python
if (A == B) or (C != D):
A = 0
elif (A > B) and (C == D):
B = 0
Visual Basic
If (A = B) Or (C <> D) Then
A = 0
Else
If (A > B) And (C = D) Then
B = 0
End If
End If
Java
if (A == B) or (C != D) {
A = 0;
}
else {
if ((A > B) and (C = D)) {
B = 0;
}
}
c FOR Times = 1 TO 20
FOR Count = 1 TO 10
OUTPUT Count
NEXT Count
NEXT Times
d Python
for Times in range(20):
for Count in range(10):
print(Count + 1)
Visual Basic
Module Module1

Sub Main()
Dim Count, Times As Integer
For Times = 1 To 20
For Count = 1 To 10
Console.Write(Count)
Next
Console.WriteLine()
Next

Console.ReadKey()
End Sub
End Module

Cambridge IGCSE and O Level Computer Science Teacher's Guide 32


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Java
import java.util.*;
class Q9Java
{
public static void main(String args[])
{

int Count, Times;


for (Times = 1; Times <= 20; Times++) {
for (Count = 1; Count <= 10; Count++) {
System.out.print(Count);
}
System.out.println();
}

}
}
10 Tasks that are repeated many times in an algorithm make use of procedures and functions.
Use of these can reduce the size of a program.
Procedures and functions are defined once and called many times. They can be written with
and without parameters. They are the variables that store the values passed to a procedure or
function.
Functions always return a value and the value can be used on the right-hand side of an
assignment statement.
A variable that can be used in any part of a program is called a global variable. A variable that
is declared within a procedure or function is called a local variable.
11 a Library routines are fully tested and ready to be incorporated into a program …
… they perform many types of task that need to be used regularly.
b 1 MOD
2 DIV
3 ROUND
4 RANDOM
c Python
import random

Number1 = int(random.random() * 10 + 10)


Number2 = int(random.random() * 10 + 10)
print(Number1, "is the first random integer between 10 and 20")
print(Number2, "is the second random integer between 10 and 20")

AnswerMod = Number1 % Number2


AnswerDiv = Number1 // Number2

print(Number1, "MOD", Number2, "is", AnswerMod)


print(Number1, "DIV", Number2, "is", AnswerDiv)

Cambridge IGCSE and O Level Computer Science Teacher's Guide 33


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Visual Basic
Module Module1

Sub Main()
Dim Number1, Number2 As Integer
Dim AnswerMod, AnswerDiv As Integer
Randomize()
Number1 = CInt(Rnd() * 10 + 10)
Number2 = CInt(Rnd() * 10 + 10)
Console.WriteLine(Number1 & " is the first random integer
between 10 and 20")
Console.WriteLine(Number2 & " is the second random integer
between 10 and 20")

AnswerMod = Number1 Mod Number2


AnswerDiv = Number1 \ Number2

Console.WriteLine(Number1 & " MOD " & Number2 & " is " &
AnswerMod)
Console.WriteLine(Number1 & " DIV " & Number2 & " is " &
AnswerDiv)

Console.ReadKey()

End Sub

End Module
Java
import java.util.Scanner;
import java.lang.Math;
import java.util.Random;

class Q11Java
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
int Number1, Number2;
Random rand = new Random();
Number1 = rand.nextInt(10) + 10;
Number2 = rand.nextInt(10) + 10;

System.out.println(Number1 + " is the first random integer


between 10 and 20");
System.out.println(Number2 + " is the second random
integer between 10 and 20");
int AnswerMod = Number1 % Number2;
int AnswerDiv = Number1 / Number2;

System.out.println(Number1 + " MOD " + Number2 + " is " +


AnswerMod);
System.out.println(Number1 + " DIV " + Number2 + " is " +
AnswerDiv);

}
}

Cambridge IGCSE and O Level Computer Science Teacher's Guide 34


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

12 a array: a data structure containing several elements of the same data type; these elements
can be accessed using the same identifier name
array dimension: dimension determined by how many index numbers are needed to
locate a piece of data, for instance a one-dimensional array only needs one index number,
a two dimensional array needs two index numbers, and so on
array index: identifies the position of an element in an array
b DECLARE OXO : ARRAY[3, 3] OF CHAR

DECLARE PROCEDURE ShowGame()


DECLARE RowIndex, ColumnIndex : INTEGER
FOR RowIndex m 1 TO 3
PRINT OXO[RowIindex,1], OXO[RowIindex,2], OXO[RowIindex,3]
NEXT
ENDPROCEDURE
c Python
OXO =[["O"," "," "],[" ", "X", " "],[" ", "X", "X"]]
def PrintStateOfGame():
print(OXO[0])
print(OXO[1])
print(OXO[2])

PrintStateOfGame()
Visual Basic
Module Module1
Public OXO = New String(2, 2) {{"O", " ", " "}, {" ", "X", " "},
{" ", "X", "O"}} 'OXO must be declared as a public/global variable

Sub Main()
PrintStateOfGame()
Console.ReadKey()
End Sub
Sub PrintStateOfGame()
Dim RowCounter, ColumnCounter As Integer
For RowCounter = 0 To 2
For ColumnCounter = 0 To 2
Console.Write(OXO(RowCounter, ColumnCounter))
Next
Console.WriteLine()
Next
End Sub
End Module
Java
import java.util.*;

class Q12Java

{
public static String[][] OXO = {{"O", " ", " "}, {" ", "X", " "},
{" ", "X", "O"}};

static void PrintStateOfGame()


{
int RowCounter, ColumnCounter;
for (RowCounter = 0; RowCounter <= 2; RowCounter++){
for (ColumnCounter = 0; ColumnCounter <= 2; ColumnCounter++){
System.out.print(OXO[RowCounter][ColumnCounter]);
}
System.out.println();
}

Cambridge IGCSE and O Level Computer Science Teacher's Guide 35


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

public static void main(String args[])


{
PrintStateOfGame();
}
13 a Data that will be required again will be lost if it is only in RAM when the computer is
switched off …
… if data is stored in a file, it can be accessed by the same or another program at a later date.
b i DECLARE Text : STRING
DECLARE MyFile : STRING

MyFile m "MyFile.txt"
Text m "Test"
OPEN MyFile FOR WRITE
WRITEFILE, Text
CLOSEFILE(MyFile)
ii OPEN MyFile FOR READ
READFILE, Text
OUTPUT Text
CLOSEFILE(MyFile)
c Python
MyFile = open("MyFile.txt","w")
Text = "Test"
MyFile.write(Text)

print("The file contains this line of text")


MyFile = open("MyFile.txt","r")
Text = MyFile.read()
print(Text)
Visual Basic
Imports System.IO
Module Module1
Sub Main()
Dim Text As String
Dim objMyFileWrite As StreamWriter
Dim objMyFileRead As StreamReader
objMyFileWrite = New StreamWriter("MyFile.txt")
Console.Write("Please enter a line of text ")
Text = "Test"
objMyFileWrite.WriteLine(Text)
objMyFileWrite.Close()

objMyFileRead = New StreamReader("MyFile.txt")


Text = objMyFileRead.ReadLine()
Console.Write("The file contains this line of text ")
Console.WriteLine(Text)
objMyFileRead.Close()
End Sub
End Module

Cambridge IGCSE and O Level Computer Science Teacher's Guide 36


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Java
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

class TextFile {

public static void main(String[] args) {


String Text;
try {
FileWriter myFileWriter = new FileWriter("MyFile.txt", false);
PrintWriter myPrintWriter = new PrintWriter(myFileWriter);

Text = "Test";
myPrintWriter.printf("%s" + "%n", Text);
myPrintWriter.close();
} catch (IOException e) {
e.printStackTrace();
}

try {
FileReader myFileReader = new FileReader("MyFile.txt");
BufferedReader myBufferReader = new BufferedReader(myFileReader);

Text = myBufferReader.readLine();
System.out.print("The file contains this line of text ")
System.out.println(Text);

myFileReader.close();

} catch (IOException e) {
e.printStackTrace();
}
}

}
14 a–e:
Python
#### Part b ###
def NewPassword():
MyPassword = input("Please enter your new password ")
Valid = True
Length = len(MyPassword)
if Length > 20:
print("Too long")
Valid = False
if Length < 10:
print("Too short")
Valid = False

Cambridge IGCSE and O Level Computer Science Teacher's Guide 37


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Counter = 0
NoSpace = True
while (Counter < Length and NoSpace):
if MyPassword[Counter:Counter + 1] == " ":
print("Spaces not allowed")
Valid = False
NoSpace = False
Counter = Counter + 1

Counter = 0
UpperCase = False
while (Counter < Length and not UpperCase):
if "A" <= MyPassword[Counter:Counter + 1] <= "Z":
UpperCase = True
Counter = Counter + 1
if (not UpperCase):
print("No uppercase letter")
Valid = False

Counter = 0
Digit = False
while (Counter < Length and not Digit):
if "0" <= MyPassword[Counter:Counter + 1] <= "9":
Digit = True
Counter = Counter + 1
if (not Digit):
print("No digit")
Valid = False

if Valid:
print("Password accepted")
MyFile = open("MyPassword.txt","w") #### Part c ###
MyFile.write(MyPassword) #### Part c ###
else:
print("Password rejected")

Cambridge IGCSE and O Level Computer Science Teacher's Guide 38


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

#### Part d ###

def CheckPassword():
MyPassword = input("Please enter your password ")
MyFile = open("MyPassword.txt","r")
StoredPassword = MyFile.read()
if MyPassword == StoredPassword:
print("Password matches")
else:
print("Password does not match")

#### Part e ###

def ChangePassword():
MyPassword = input("Please enter your password ")
MyFile = open("MyPassword.txt","r")
StoredPassword = MyFile.read()

if MyPassword == StoredPassword:
NewPassword()
else:
print("Password incorrect cannot change")

#### Part a ###

Quit = False
while not Quit:
print (" Password Management")
print (" 1. Enter a new password")
print (" 2. Check your password")
print (" 3. Change your password")
print (" 4. Quit")

option = int(input("Please enter your chosen option "))

Cambridge IGCSE and O Level Computer Science Teacher's Guide 39


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

if option == 1:
NewPassword()
elif option == 2:
CheckPassword()
elif option == 3:
ChangePassword()
elif option == 4:
Quit = True
else:
print ("Incorrect option chosen")

Visual Basic
Imports System.IO
Module Module1

'*** Part a ***


Sub Main()
Dim Opt As Integer
Dim Quit As Boolean = False
Dim MyPassword As String

While Not Quit


Console.WriteLine(" Password Management")
Console.WriteLine(" 1. Enter a new password")
Console.WriteLine(" 2. Check your password")
Console.WriteLine(" 3. Change your password")
Console.WriteLine(" 4. Quit")

Console.Write("Please enter your chosen option ")


Opt = Integer.Parse(Console.ReadLine())

Cambridge IGCSE and O Level Computer Science Teacher's Guide 40


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Select Case Opt


Case 1
Console.Write("Please enter your password ")
MyPassword = Console.ReadLine()
NewPassword(MyPassword)
Case 2
Console.Write("Please enter your password ")
MyPassword = Console.ReadLine()
CheckPassword(MyPassword)
Case 3
Console.Write("Please enter your password ")
MyPassword = Console.ReadLine()
ChangePassword(MyPassword)
Case 4
Quit = True
Case Else
Console.WriteLine("Incorrect option chosen")
End Select

Console.ReadKey()

End While

End Sub
'******

Cambridge IGCSE and O Level Computer Science Teacher's Guide 41


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

'*** Part b ***


Sub NewPassword(MyString As String)
Dim Length, Counter As Integer
Dim Valid, NoSpace, UpperCase, Digit As Boolean
Dim objMyFileWrite As StreamWriter

Valid = True
Length = Len(MyString)
If Length > 20 Then
Console.WriteLine("Too long")
Valid = False
End If
If Length < 10 Then
Console.WriteLine("Too short")
Valid = False
End If

Counter = 0
NoSpace = True
While Counter < Length And NoSpace
If MyString.Substring(Counter, 1) = " " Then
Console.WriteLine("Spaces not allowed ")
Valid = False
NoSpace = False
End If
Counter = Counter + 1
End While

Cambridge IGCSE and O Level Computer Science Teacher's Guide 42


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Counter = 0
UpperCase = False
While Counter < Length And Not UpperCase
If MyString.Substring(Counter, 1) >= "A" And
MyString.Substring(Counter, 1) <= "Z" Then
UpperCase = True
End If
Counter = Counter + 1
End While
If Not UpperCase Then
Console.WriteLine("No uppercase letter")
Valid = False
End If

Counter = 0
Digit = False
While Counter < Length And Not Digit
If MyString.Substring(Counter, 1) >= "0" And
MyString.Substring(Counter, 1) <= "9" Then
Digit = True
End If
Counter = Counter + 1
End While
If Not Digit Then
Console.WriteLine("No digit")
Valid = False
End If
If Valid Then
Console.WriteLine("Password accepted. Press any
key to continue.")
objMyFileWrite = New
StreamWriter("MyPassword.txt")'*** Part c ***
objMyFileWrite.WriteLine(MyString)'*** Part c ***
objMyFileWrite.Close()'*** Part c ***
Else

Cambridge IGCSE and O Level Computer Science Teacher's Guide 43


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Console.WriteLine("Password rejected. Press any


key to continue.")
End If

End Sub
'******

'**** Part d ***


Sub CheckPassword(MyString As String)
Dim objMyFileRead As StreamReader
Dim StoredPassword As String
objMyFileRead = New StreamReader("MyPassword.txt")
StoredPassword = objMyFileRead.ReadLine
objMyFileRead.Close()

If MyString = StoredPassword Then


Console.Write("Password matches. Press any key to
continue.")
Else
Console.WriteLine("Password does not match. Press
any key to continue.")
End If

End Sub
'******

'*** Part e ***


Sub ChangePassword(MyString As String)
Dim NewWord As String
Dim objMyFileRead As StreamReader
Dim StoredPassword As String
objMyFileRead = New StreamReader("MyPassword.txt")
StoredPassword = objMyFileRead.ReadLine()
objMyFileRead.Close()

Cambridge IGCSE and O Level Computer Science Teacher's Guide 44


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

If MyString = StoredPassword Then


Console.Write("Please enter your new password ")
NewWord = Console.ReadLine()
NewPassword(NewWord)
Else
Console.WriteLine("Password incorrect cannot
change. Press any key to continue.")
End If

End Sub
'******

End Module

Java
import java.util.*;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

class Chapter8Q14 {
// *** Part b ***
static void NewPassword(String MyString) {
int Length;
Length = MyString.length();
boolean Valid = true;

if (Length > 20) {


System.out.println("Too long");
Valid = false;
}

Cambridge IGCSE and O Level Computer Science Teacher's Guide 45


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

if (Length < 10) {


System.out.println("Too short");
Valid = false;
}

int Counter = 0;
boolean NoSpace = true;

while ((Counter < Length) & NoSpace) {


if (MyString.substring(Counter,Counter +
1).compareTo( " ") == 0) {
System.out.println("Spaces not allowed");
Valid = false;
NoSpace = false;
}
Counter ++;

Counter = 0;
boolean UpperCase = false;
while ((Counter < Length) & !UpperCase) {
if (MyString.charAt(Counter) >= 'A' &&
MyString.charAt(Counter) <= 'Z') {
UpperCase = true;
}
Counter ++;
}
if(!UpperCase) {
System.out.println("No uppercase letter");
Valid = false;
}

Cambridge IGCSE and O Level Computer Science Teacher's Guide 46


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

Counter = 0;
boolean Digit = false;
while ((Counter < Length) & !Digit) {

if (MyString.charAt(Counter) >= '0' &&


MyString.charAt(Counter) <= '9') {
Digit = true;
}
Counter ++;
}
if(!Digit) {
System.out.println("No digit");
Valid = false;
}

if (Valid) {
System.out.println("Password accepted");
try {
FileWriter myFileWriter = new
FileWriter("MyPassword.txt", false); //***
Part c ***
PrintWriter myPrintWriter = new
PrintWriter(myFileWriter); //*** Part c ***
myPrintWriter.printf("%s" + "%n", MyString);
//*** Part c ***
myPrintWriter.close(); //*** Part c ***
} catch (IOException e) { //*** Part c ***
e.printStackTrace(); //*** Part c ***
}
}
else {
System.out.println("Password rejected");
}
}

Cambridge IGCSE and O Level Computer Science Teacher's Guide 47


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

// ******

// *** Part d ***


static void CheckPassword(String MyString) {
String StoredPassword = "";

try {
FileReader myFileReader = new
FileReader("MyPassword.txt");
BufferedReader myBufferReader = new
BufferedReader(myFileReader);
StoredPassword = myBufferReader.readLine();
myFileReader.close();
} catch (IOException e) {
e.printStackTrace();
}

if (MyString.compareTo(StoredPassword) == 0) {
System.out.println("Password matches");
}
else {
System.out.println("Password does not match");
}

}
//******

Cambridge IGCSE and O Level Computer Science Teacher's Guide 48


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

// *** Part e ***


static void ChangePassword(String MyString) {
Scanner myObj = new Scanner(System.in);
String StoredPassword = "";
String NewWord = "";

try {
FileReader myFileReader = new
FileReader("MyPassword.txt");
BufferedReader myBufferReader = new
BufferedReader(myFileReader);
StoredPassword = myBufferReader.readLine();
myFileReader.close();
} catch (IOException e) {
e.printStackTrace();
}

if (MyString.compareTo(StoredPassword) == 0) {
System.out.print("Please enter your new password ");
NewWord = myObj.nextLine();
NewPassword(NewWord);
}
else {
System.out.println("Password incorrect cannot
change");
}
}
//******

Cambridge IGCSE and O Level Computer Science Teacher's Guide 49


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

// *** Part a ***


public static void main(String args[]) {
Scanner myObj = new Scanner(System.in);
boolean Quit = false;
while (!Quit) {
System.out.println(" Password Management");
System.out.println(" 1 Enter a new password");
System.out.println(" 2 Check your password");
System.out.println(" 3 Change your password");
System.out.println(" 4 Quit");

System.out.print("Please enter your chosen option ");


int option = myObj.nextInt();

String MyPassword = myObj.nextLine();

switch (option) {
case 1:
System.out.print("Please enter your
password ");
MyPassword = myObj.nextLine();
NewPassword(MyPassword);
break;
case 2:
System.out.print("Please enter your
password ");
MyPassword = myObj.nextLine();
CheckPassword(MyPassword);
break;
case 3:
System.out.print("Please enter your
password ");
MyPassword = myObj.nextLine();
ChangePassword(MyPassword);
break;
case 4:
Quit = true;
break;

Cambridge IGCSE and O Level Computer Science Teacher's Guide 50


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

default:
System.out.println("Incorrect option
chosen");
}
}
//******
}
}
b Test data Expected output Actual output
Password Too short
No digit
Password rejected
Password99 Password accepted

password99 No uppercase letter


Password rejected
Password99! Password accepted

ExtraLargePassword9999999 Too long


Password rejected
21 Too short
Spaces not allowed
No uppercase letter
Password rejected

15 Important points to note when writing your program:


x There is not one 'correct' solution to this problem. Any solution is acceptable but your
program must:
x perform all the tasks set out in the question
x use a range of appropriate programming techniques that cover all the tasks set out in
the question. These tasks must be executed by your program in a logical order
x use appropriate data structures, which have been given meaningful names, to store all
the data mentioned in the question. If any data structures are named in the question,
then those names must be used in your program
x be fully commented to ensure that it can be understood
x The array name must be Game[]
x All other data structures must have meaningful names.

Cambridge IGCSE and O Level Computer Science Teacher's Guide 51


© David Watson and Helen Williams 2021
Answers to Algorithms, Programming and Logic Workbook

x Procedures must be used, for example to:


x set up an empty array at the start of each game
x display the contents of the array
x enter a player’s move – this could use a parameter for O or X
x check for a winner
x Your program must be fully commented.
x Your answer to 12 will help you to start your program.

9 Databases
1 a • table: a collection of records …
x … where each record contains data about a similar item, e.g. a student.
x record: a collection of fields about the same item …
x … there are the same number of fields in each record.
x field: a single piece of data …
x … that is given a data type.
b Four from:
x text/alphanumeric – e.g. a description of a part
x character – e.g. S, M or L for the size of a part
x Boolean – e.g. true or false, sold or not
x integer – e.g. number of parts in stock
x real – e.g. price of an item 12.99
x date/time – e.g. a date such as 18/12/2020
2 a Field 1: Type
Data type: text
Reason: as the name given to the type of ice cream is a series of characters
Sample: choc ice
Field 2: Flavour
Data type: text
Reason: as the name given to the flavour of ice cream is a series of characters
Sample: vanilla
Field 3: Size
Data type: text
Reason: as the size of the ice cream is stored as a word
Sample: Small
Field 4: NumberInStock
Data type: integer
Reason: as the number in stock will be a whole number
Sample: 

Cambridge IGCSE and O Level Computer Science Teacher's Guide 52


© David Watson and Helen Williams 2021

You might also like