igcse_compsci_2ed_java_sol
igcse_compsci_2ed_java_sol
Sample answers have been written by the authors. In examinations, the way marks are awarded may be different. References to
assessment and/or assessment preparation are the publisher’s interpretation of the syllabus requirements and may not fully reflect
the approach of Cambridge Assessment International Education.
A note about identifiers in pseudocode: The identifiers, which include variable, procedure and function names, given in exam
questions will be in mixed case, for example, NumberOfPlayers. When using pseudocode to answer questions you must use
the exact same variable name for any variables given in the question. When you are creating your own variable names in your
pseudocode answers, it is quite normal to use the syntax that is used in your preferred programming language, for example in Java,
numberOfPlayers. You must ensure that your algorithm is correct and unambiguous and that the identifiers chosen are consistent
throughout your solution
S
olutions
Chapter 1: Introduction to Java
End-of-chapter questions
1 Java Byte Code.
2 JDK is used when source code is being written. It contains a compiler for translating
source code into Java Byte Code. JRE is used when a program is to be run and the
Java Byte Code has been provided. It runs the program by translating the Java Byte Code.
Chapter 2: Algorithms
Practice tasks
2.1 Choice of who is white should be made before pieces are placed on the chessboard.
Calculate percentage
1
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Calculate percentage
Output grade
2.4
START
Input total
possible mark
Input mark
Calculate
percentage
Output
percentage
STOP
2
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Challenge tasks
2.1 Input two numbers
Input operation name
Calculate answer as a sum if addition
Calculate answer as a product if multiplication
Calculate answer as a difference if subtraction
Output answer
2.2 A sensible answer here is to have a design that allows for a candidate to have taken more than
one exam. As well as handling two or more marks, the design might include the calculation of an
average percentage mark with the grade being calculated for this average mark. The design could
use an iteration but this is not necessary. The following is a possible design.
Input total mark possible for each exam
Input candidate identifier
Input candidate mark for each exam
Calculate percentage for each exam
Calculate average percentage
Grade as Distinction if average percentage above 80
Grade as Merit if average percentage in range 61–80
Grade as Pass if average percentage in range 40–60
Grade as Fail if average percentage less than 40
Look up candidate name
Output candidate name and grade
3
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
2.3 As this is a preliminary design, we are allowed to leave out many details. Here there is no
indication how looking up a candidate name would be done. Also the process box for
calculating the grade does not show the decisions to be made.
START
Input identifier
Calculate percentage
for each exam
Calculate average
percentage
Calculate grade
Look up name
Output name
and grade
STOP
4
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
A more detailed design would expand the calculate grade process box to include three
successive diamond shapes as shown here.
> 80 Distinction
TRUE
FALSE
61 – 80 Merit
TRUE
FALSE
40 – 60 Pass
FALSE TRUE
Fail
End-of-chapter questions
1 i Algorithm: A series of actions required to achieve a specific outcome.
ii Logic construct: A means of controlling the order in which algorithm actions are performed.
iii Sequence: A logic construct where individual actions in an algorithm follow one after
another in order.
2
Either input or output
5
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
3
START
Input number
bought
Add to total
FALSE
Output total
price to pay
STOP
Practice tasks
3.1 For the name, one variable of type String could be used. However, it would be more likely
that a given name and a family name would be separately stored in two variables.
6
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Recording the number of years and the number of months would fit most purposes.
Note that using integer values is an alternative but the program would not be as useful.
START
Input length
Input width
Input depth
Output volume
STOP
7
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
3.4 For this scenario, declaration statements have been included in the pseudocode. This is always
an option. You can include declaration statements if you think they will be helpful. You never
include declaration statements in a flowchart. You can also include initialisation, but for a simple
short program such as this there is no requirement to do so.
For this program design, the assumption has been made that the coverage will remain the same
whenever the program is used but that the price of grass seed will vary.
CONSTANT seedCoverage 50.0
DECLARE lawnLength, lawnWidth, lawnArea: REAL
DECLARE seedPrice, seedNeeded, seedNeededCost: REAL
INPUT lawnLength
INPUT lawnWidth
INPUT seedPrice
lawnArea lawnLength * lawnWidth
seedNeeded lawnArea * seedCoverage / 1000
seedNeededCost seedNeeded * seedPrice
OUTPUT seedNeeded
OUTPUT seedNeededCost
The corresponding flowchart is:
START
seedCoverage ← 50.0
INPUT lawnLength
INPUT lawnWidth
INPUT seedPrice
OUTPUT seedNeeded
OUTPUT seedNeededCost
STOP
8
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
If the decision was made to allow coverage to vary, the Java code for declaration
and calculation would be:
float seedCoverage;
float lawnLength, lawnWidth, lawnArea;
float seedPrice, seedNeeded, seedNeededCost;
lawnArea = lawnLength * lawnWidth;
seedNeeded = lawnArea * seedCoverage / 1000;
seedNeededCost = seedNeeded * seedPrice
b Declarations:
float standardSingleFare, ticketPrice, totalPrice;
float discountForReturn, discount ForChild, discountAdvance;
String departureStation, arrivalStation;
int numberOfTickets, age;
boolean singleTicket, advanceBooking;
String dateOfBooking, dateOfTravel;
c Assignment statements:
ticketPrice = standardSingleFare;
totalPrice = ticketPrice + ticketPrice * discountForChild;
9
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Challenge tasks
3.1 The grandmother can be ignored because her tickets are free. Then the mother and father are just
dealt with as two people. Because there are only four tickets being bought there is no discount for
the advance booking. We have the following individual contributions to the price.
standardSingleFare * 2
standardSingleFare * discountForReturn * 2
standardSingleFare * discountForChild
standardSingleFare * discountForChild * discountForReturn
totalPrice = s
tandardSingleFare * 2 * (1 + discountForReturn)
+ standardSingleFare * discountForChild *
(1 + discountForReturn);
It should be noted that this approach is using the discount as a multiplying factor. So if a price
was $40 and the discount was stored as 0.25 then the cost of the return journey ticket would be
$10. This is not the only way that a discount could be applied. An alternative would be to subtract
the $10 from the $40 to give a price of $30 for the return.
Pseudocode design:
CONSTANT bagCapacity 25
INPUT bagPrice
INPUT amountOfGrain
amountOfGrain amountOfGrain * 95 / 100
numberOfBags amountOfGrain / bagCapacity
totalPrice numberOfBags * bagPrice
OUTPUT numberOfBags
OUTPUT totalPrice
There is no need for calculations using real values. The pseudocode design you have
just read will calculate the number of full bags to a good approximation.
10
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Note that the assignment statements could be merged into one if you wished.
Pseudocode design:
INPUT poolVolume
INPUT drainageRate
minutesToDrain poolVolume / drainageRate
hoursToDrain minutesToDrain / 60
minutes hoursToDrain * 60
minutesToDrain minutesToDrain – minutes
OUTPUT hoursToDrain
OUTPUT minutesToDrain
(Later in this book you will learn how this can be done with less code.)
11
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Whenever painting is being done, there is an expectation that there will be some unused paint
left over. This is because a painter does not wish to run out of paint before the job is finished.
The values chosen for the input values given as integer values will be cautious. For example,
if the tinCoverage was described on the tin as 4.5 square metres, this would be entered as 4
not as 5. Having said that, the units chosen for the dimensions must be sensible. If the length were
1.5 metres, it would be sensible to use centimetres for the unit, not metres.
Accuracy is best achieved by including the number of coats in the area calculation before the
number of tins is calculated. The addition of an extra tin is just to make sure there is enough
paint.
Pseudocode design:
INPUT lengthOfWall
INPUT heightOfWall
INPUT numberOfCoats
INPUT tinCoverage
areaToPaint (lengthOfWall * heightOfWall) * numberOfCoats
numberOfTins areaToPaint / tinCoverage
numberOfTins numberOfTins + 1
OUTPUT numberOfTins
+ timeForBreak * 2;
2 If your version is different to the one given here, you can supply some simple values for the
variables and do individual calculations by hand to check they give the same result. However,
to be sure that you were correctly applying the rules of precedence, you would need to write
programs in Java which incorporated the different versions.
12
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
3 Use parentheses.
Sometimes you will use parentheses to impose a particular sequence for the evaluation
of an expression. In other cases you will find that using parentheses produces a neat
expression which is easy to understand.
The following is suggested as a solution that makes the best use of parentheses:
timeForTravel = 1.1 * ((distance1 + distance2 + distance3) /
averageSpeed + timeForBreak * 2);
End-of-chapter questions
1 a There is a defined number of bits allocated in memory.
2 Pseudocode:
For the Java code it must be remembered that the marks will be integer values.
However, unless the total mark for the paper is 100 the percentage calculated will not always be
an integer. Therefore the Java code must prevent the division being handled as integer division.
The following code does this.
percentageMark = candidateMark * 100.0 / totalMarkPossible;
3 Identifier table:
4 INPUT distanceOfJourney
INPUT fixedCost
INPUT extraCostPerMile
totalCharge fixedCost + (distanceOfJourney – 2) * extraCostPerMile
OUTPUT totalCharge
13
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
}}
When you run this program you are likely to get the following error message:
FloatTest1.java:10: error: incompatible types: possible lossy
conversion from double to float
float sum = 0.0;
^
FloatTest1.java:14: error: incompatible types: possible lossy
conversion from double to float
sum = 10.0 + number1;
^
2 errors
Both of the following programs should work correctly. If you enter 5, the program outputs
15.0 as an answer for the sum.
import java.util.Scanner;
/*
calculates sum and average
*/
class FloatTest2 {
public static void main(String[] args) {
float sum = 0.0f;
System.out.println("Please enter a number");
Scanner mynum = new Scanner(System.in);
float number1 = mynum.nextFloat();
sum = 10.0f + number1;
14
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
15
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
16
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Challenge tasks
4.1 import java.util.Scanner;
/*
to illustrate arithmetic
*/
class BagsOfGrain {
public static void main(String[] args) {
final int bagCapacity = 25;
int bagPrice, amountOfGrain, numberOfBags, totalPrice;
17
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
End-of-chapter questions
1 There should be a prompt output by the program telling the user what needs to be input.
System.out.println("Enter the length of the wall");
Scanner number1Input = new Scanner(System.in);
lengthOfWall = number1Input.nextInt();
18
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
2 In the first of the three lines shown below, the coding should have myObj2.
In the third line shown here, the coding should have answer1.
number2 = myObj1.nextInt();
answer1 = number1 + number2;
System.out.println(answer);
The lack of any text to explain the output is bad practice, but not an actual error.
3 A char value for a variable cannot be input. Later in the book you will meet a solution for this.
At this stage, you might perhaps suggest entering an integer value that could be used as a code for
a character.
4 import java.util.Scanner;
class FarmersBulkBuy {
public static void main(String[] args) {
19
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Chapter 5: Selection
Practice tasks
5.1 Rule 1
a int age;
boolean withParent;
I t must be acknowledged that a child under the age of five years old is unlikely
to be travelling without a parent. Ignoring that, the logic here is sensible.
Rule 2
a
boolean student;
boolean withStudentCard;
Rule 3
a boolean seasonTicket;
String travelDate, expiryDate;
20
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
5.3 The flowchart only has three decision symbols and the first action is to test a condition.
This means that this is only suitable for the first example of pseudocode shown in
Option 2 in Skills Focus 5.2.
Note that because of the use of the nested construct, it is only necessary to test one condition
for the Merit and Pass decisions. For example, if the percent is 81 +, the flow of the algorithm
ignores all of the later decisions.
TRUE
FALSE
TRUE
FALSE
TRUE
FALSE
grade "Fail"
21
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
5.4 The sensible choice is the second approach discussed in Option 2 in Skills Focus 5.2,
where there is an initialisation before any conditions are tested.
grade ← "Fail"
TRUE
FALSE
TRUE
percent > 60? grade ← "Merit"
FALSE
TRUE
FALSE
5.5 The following is the program for the design in Practice task 5.4.
import java.util.Scanner;
/*
percent to Distinction, Merit, Pass or Fail
*/
class PercentToGrade {
public static void main(String[] args) {
int percent;
String grade = "Fail";
System.out.println("Enter percentage mark");
Scanner myObj = new Scanner(System.in);
percent = myObj.nextInt();
if (percent > 80)
grade = "Distinction";
else if (percent > 60)
grade = "Merit";
22
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
int stationNumber = 0;
int priceToPay = 0;
switch (stationNumber)
{
case 1:
{
System.out.println("Ticket price is $" + station1Price);
break;
}
case 2:
{
System.out.println("Ticket price is $" + station2Price);
break;
}
case 3:
{
System.out.println("Ticket price is $" + station3Price);
break;
}
case 4:
{
System.out.println("Ticket price is $" + station4Price);
break;
}
default: System.out.println("unrecognised station");
}
}}
23
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Challenge tasks
5.1 import java.util.Scanner;
/*
to calculate the ticket price for one person
*/
class TicketOnePerson {
public static void main(String[] args) {
System.out.println("Enter age");
Scanner number1Input = new Scanner(System.in);
age = number1Input.nextInt();
24
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
break;
case 5: {
priceToPay = standardPrice;
System.out.println("Price for single is $" + priceToPay);
priceToPay = priceToPay * 0.2;
System.out.println("return price is $" + priceToPay);
}
}
}}
The following is a possible Java program. Note that integer values are input. This is a simple
solution available when the input values are only going to be tested in the program to direct
which action is taken. The input values are not going to be used for anything else.
25
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
import java.util.Scanner;
/*
to calculate seed needed for a lawn with chosen shape
*/
class LawnCalculation {
public static void main(String[] args) {
int lawnShape, choice;
double width, length, diameter;
double area = 0.0;
double areaCutOut = 0.0;
double seedCoverage, seedNeeded;
26
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
}}
27
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
ELSE
category "Normal"
ENDIF
4 The following is the Java code corresponding to the fragment of pseudocode used to
illustrate the concept:
else if (candidateMark > 60)
if (candidateMark < 81)
grade = "Merit";
The following is a complete Java program that has removed all of the original range
checks and is now a fully nested solution. The nested code is presented in bold.
import java.util.Scanner;
/*
percent to Distinction, Merit, Pass or Fail
*/
class GradeTest {
public static void main(String[] args) {
int candidateMark = 0;
String grade = "";
End-of-chapter questions
1 ELSE
OUTPUT "the values are equal"
ENDIF
28
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
3 a
INPUT number1
maxValue number1
INPUT number2
IF number2 = number1
THEN
OUTPUT "enter a different value"
INPUT number2
ENDIF
IF number2 > maxValue
THEN
maxValue number 2
ENDIF
INPUT number3
IF number3 = number1 OR number3 = number2
THEN
OUTPUT " Enter a different value from those
entered previously"
INPUT number3
ENDIF
IF number3 > maxValue
maxValue number3
ENDIF
OUTPUT maxValue
b import java.util.Scanner;
/*
to find highest number
*/
class HighestValue {
public static void main(String[] args) {
int number1, number2, number3, maxValue;
System.out.println("Enter first number");
Scanner number1Input = new Scanner(System.in);
number1 = number1Input.nextInt();
maxValue = number1;
System.out.println("Enter second number");
Scanner number2Input = new Scanner(System.in);
number2 = number2Input.nextInt();
if (number1 == number2)
{
System.out.println("duplicate, enter a different number");
Scanner number3Input = new Scanner(System.in);
number2 = number3Input.nextInt();}
if (number2 > maxValue) maxValue = number2;
System.out.println("Enter third number");
29
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
4 D is false.
The expression has three options for the value to be true. These are separated by OR.
Chapter 6: Iteration
Practice tasks
6.1 import java.util.Scanner;
/*
the iteration example calculating multiples
*/
class Multiples {
public static void main(String[] args) {
int multiple = 0;
System.out.println("Please enter your number");
Scanner numberInput = new Scanner(System.in);
int number = numberInput.nextInt();
System.out.println("Please enter number of multiples");
Scanner multiplesInput = new Scanner(System.in);
int numberOfMultiples = multiplesInput.nextInt();
for (int i = 1; i <= numberOfMultiples; i++)
{
multiple = i * number;
System.out.println(multiple);
}
}}
30
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
31
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
32
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Challenge tasks
6.1
START
i←1
dTot ← 0
mTot ← 0
pTot ← 0
fTot ← 0
FALSE
grade ← "Merit"
percent > 60?
mTot ← mTot + 1
TRUE
FALSE
grade ← "pass"
percent >= 40?
pTot ← pTot + 1
TRUE
FALSE
grade ← "Fail"
OUTPUT grade
fTot ← fTot + 1
TRUE
i <= 10 i←i+1
FALSE
STOP
import java.util.Scanner;
/*
grading and counting number of grades
*/
class CountingGrades {
public static void main(String[] args) {
int percent;
int dTotal = 0;
int mTotal = 0;
int pTotal = 0;
33
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
int fTotal = 0;
String grade = "";
34
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
if (category> 0)
{
switch (category)
{
case 1: {
priceToPay = standardPrice / 4;
totalPriceToPay = totalPriceToPay + priceToPay;
}
break;
case 2: {
priceToPay = standardPrice / 4 + standardPrice / 8;
totalPriceToPay = totalPriceToPay + priceToPay;
}
break;
case 3: {
priceToPay = standardPrice;
totalPriceToPay = totalPriceToPay + priceToPay;
}
break;
case 4: {
priceToPay = standardPrice + standardPrice / 2;
totalPriceToPay = totalPriceToPay + priceToPay;
}
}
}
System.out.println("Enter age");
Scanner number2Input = new Scanner(System.in);
age = number2Input.nextInt();
}
System.out.println("Total to pay is $" + totalPriceToPay);
}}
35
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
int numberToBeTested = 0;
int i = 2;
boolean prime = true;
int theModulus = 0;
36
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
End-of-chapter questions
1 a For loop, While loop, Do while loop
c The condition in the For loop is tested after each iteration. The test is to see if another
iteration is allowed. The test applies to the value of the loop control variable.
The condition in the While loop is also tested after each iteration. The test is again to see
if a further iteration is allowed. There is no restriction on the content of the condition.
There is no condition in the header of a Do while loop. Instead there is a condition at the
end of the loop which serves the same function, in that it controls whether or not there is
a further iteration. There is no restriction on what is tested.
2 The first example has to be that the condition controlling the loop indicates no more iterations.
A second choice would be when there is no more data to be input. This could be achieved
by a user supplying a rogue value, such as –1, to say stop. If data were being entered from a file,
then a test to show that the end of the file had been reached would be used.
Further options are where an activity has reached an endpoint, for example, when a search
has found a value or when a contestant in an online game has won.
3 a
integer2 integer1 / 2
IF integer2 * 2 = integer1
THEN
OUTPUT "integer1 is an even number"
ENDIF
b
totalOdd 0
totalEven 0
FOR i = 1 TO 10
INPUT anInteger
testInteger anInteger / 2
IF testInteger * 2 = anInteger
THEN
totalEven totalEven + 1
ELSE
totalOdd totalOdd + 1
ENDIF
NEXT i
OUTPUT "number of even numbers is " totalEven
OUTPUT "number of odd numbers is " totalOdd
c The design assumes that the number of values will be limited to 10.
37
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
4 totalValue 0
maxValue 0
numberOfValues 0
INPUT aValue
WHILE aValue <> 0.0 DO
IF aValue > maxValue
THEN
maxValue aValue
ENDIF
totalValue totalValue + aValue
numberOfValues = numberOfValues + 1
INPUT aValue
ENDWHILE
average totalValue / numberOfValues
adjustedAverage (totalValue – maxValue )/(numberOfValues – 1)
OUTPUT average
OUTPUT adjustedAverage
import java.util.Scanner;
/*
to calculate averages
*/
class Averages {
public static void main(String[] args) {
double aValue;
double average;
double adjustedAverage;
int numberOfValues = 0;
double maxValue = 0.0;
double totalValue = 0.0;
System.out.println("Enter value");
Scanner number1Input = new Scanner(System.in);
aValue = number1Input.nextFloat();
38
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Chapter 7: Subroutines
Practice tasks
7.1 import java.util.Random;
/*
the random number program
*/
class RandTest {
public static void main(String[] args) {
int sum1 = 0, sum2 = 0, sum3 = 0;
int sum4 = 0, sum5 = 0, sum6 = 0;
int randNum = 0;
}}
39
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
if (randNum == inputNum)
System.out.println("Well done");
else
System.out.println("Hard luck");
}}
40
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
41
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Challenge tasks
7.1 import java.util.Random;
import java.util.Scanner;
/*
the game with random number program extended
*/
class RandTest3 {
public static void main(String[] args) {
int randNum = 0;
int inputNum1 = 0;
int inputNum2 = 0;
int score1 = 0;
int score2 = 0;
int differ1 = 0;
int differ2 = 0;
boolean equaldiff = false;
for (int i = 1; i <= 10; i++){
System.out.println("First player enter a number in the range 1 to
100");
Scanner myObj1 = new Scanner(System.in);
inputNum1 = myObj1.nextInt();
System.out.println("Second player enter a number in the range 1
to 100");
Scanner myObj2 = new Scanner(System.in);
inputNum2 = myObj2.nextInt();
while (equaldiff)
{
System.out.println("First player enter a number in the
range 1 to 100");
Scanner myObj3 = new Scanner(System.in);
inputNum1 = myObj3.nextInt();
42
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
7.2 Note that PI is stored as a constant of type double so this program uses double for all
of the variables.
import static java.lang.Math.*;
import java.util.Scanner;
/*
to use square root method
*/
class Wallcircles {
public static void main(String[] args) {
double diameter, areaTin, areaCircle;
areaTin = 0.5 * 100 * 100;
areaCircle = areaTin / 10;
diameter = sqrt(areaCircle / PI) * 2;
System.out.println("The diameter will be " + diameter +
" centimetres");
}}
7.3 One half of the roof is a rectangle. The length is 20 m but the width has to be calculated
from 5 / width = cos 30°. The 5 comes from dividing 10 by 2.
Note again that you need to use the double type for the variables.
import static java.lang.Math.*;
import java.util.Scanner;
/*
to use trigonometry
*/
class RoofTiles {
public static void main(String[] args) {
43
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
7.2 The following code fragment will extract the last character as a value for a char variable.
int len = mySTR.length();
char myChar = mySTR.charAt(len — 1);
The following code fragment will extract the last character as a value for a String variable.
int len = mySTR.length();
String newStr = mySTR.substring(len — 1);
End-of-chapter questions
1 a An argument is a value supplied to a subroutine when a program calls the subroutine.
hen the subroutine code starts to execute, the parameter will initially have the value
W
provided by the argument.
b function returns a value to the calling program; a procedure does not return a value.
A
The function code includes a return statement that identifies the value to be returned.
The function is created with a data type defined for this return value. In the program
using the function, the function name is included in the right-hand side of an assignment
statement. When a program calls a procedure, there is no assignment statement. The name of
the procedure is just used as a statement or possibly (in some languages) the name follows the
word call. A function would not output a value but a procedure usually would do so.
44
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
c The substring method extracts a string. If used with one argument it extracts all
characters from the index position defined by the argument up to the final character in the
string. If two arguments are supplied, the second one identifies the first index position which
is not to be included in the substring.
The replace method requires two arguments. The first argument identifies one or more
characters to be replaced by those provided as the second argument. All occurrences of the
first argument are replaced.
3 If a procedure is used, the converted values can be output. The issue is how to return more than
one value if a function is used. The solution here uses an array. Arrays are explained in Chapter 8.
import java.util.Scanner;
import java.util.Arrays;
/*
using an array to return multiple values from a function
*/
public class FuncReturn{
static int[] converter(int numSeconds)
{
int numMinutes;
numMinutes = numSeconds / 60;
numSeconds = numSeconds - (numMinutes * 60);
return new int[] {numMinutes, numSeconds};
}
public static void main(String[] args) {
int number1 = 0;
System.out.println("Please enter time in seconds");
Scanner myObj1 = new Scanner(System.in);
number1 = myObj1.nextInt();
int[] times = new int[2];
times = converter(number1);
System.out.println("time is " + times[0] +
" minutes and " + times[1] + " seconds");
}}
Chapter 8: Arrays
Practice tasks
8.1 import java.util.Scanner;
/*
summing using an array
*/
class arraySum {
45
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
8.2 You need to remember that the random number is generated in the range 0 to 19
so you need to add 1 to get the range 1 to 20.
import java.util.Random;
/*
array with random numbers
*/
class RandomArray {
public static void main(String[] args) {
int[] arrayRandom = new int[10];
for (int i = 0; i <= 9; i++)
{
Random MyRand = new Random();
arrayRandom[i] = MyRand.nextInt(20);
arrayRandom[i] += 1;
}
for (int i = 0; i <= 9; i++)
{
System.out.println(arrayRandom[i]);
}
}}
8.3 The following program has created the array without any input.
The array stores multiples of 8 up to 80.
import java.util.Scanner;
/*
linear search
*/
class LinearSearch {
public static void main(String[] args) {
int[] arrayNotRandom = new int[10];
46
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
int searchValue = 0;
for (int i = 0; i <= 9; i++)
{
arrayNotRandom[i] = (i + 1) * 8;
}
boolean notFound = true;
int j = 0;
System.out.println("Enter a number you think is stored");
Scanner myObj = new Scanner(System.in);
searchValue = myObj.nextInt();
while (notFound && j < 10)
{
if (searchValue == arrayNotRandom[j]){
System.out.println(searchValue + " found in the array");
notFound = false;
}
j = j + 1;
}
if (notFound)
System.out.println(searchValue + " not found in array");
}}
8.4 This program code has the correct logic, but would be better if candidate names and
exam names were output. Well done if you included these in your program code.
import java.util.Scanner;
/*
using related arrays
*/
class ThreeArrays {
public static void main(String[] args) {
String[] names = new String[]
{"candidate1", "candidate2", "candidate3", "candidate4"};
int[] exam1 = new int[]
{45, 72, 64, 33};
int[] exam2 = new int[]
{50, 76, 54, 37};
int lastIndex = names.length;
lastIndex--;
System.out.println(" percentage marks for exam 1");
for (int i = 0; i <= lastIndex; i++)
System.out.println("mark for " +
names[i] + " is " + exam1[i]);
System.out.println(" percentage marks for exam 2");
for (int j = 0; j <= lastIndex; j++)
System.out.println("mark for " +
names[j] + " is " + exam2[j]);
}}
47
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Challenge tasks
8.1 import java.util.Scanner;
import java.util.Random;
/*
array with random numbers
*/
class countingRandom {
public static void main(String[] args) {
int[] arrayRandom = new int[50];
int[] countRandom = new int[50];
int num = 0;
int firstNum = 0;
int secondNum = 0;
//set up array containing numbers randomly generated
for (int i = 0; i <= 49; i++)
{
Random MyRand = new Random();
arrayRandom[i] = MyRand.nextInt(50);
arrayRandom[i] += 1;
}
//intialise counting array to zero values
for (int i = 0; i <= 50; i++)
countRandom[i] = 0;
// increment values in the count array
for (int i = 0; i <= 49; i++)
{
num = arrayRandom[i];
countRandom[num] = countRandom[num] + 1;
}
48
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
8.2 This can be tackled in a number of ways. You need to remember that when a user inputs a digit,
the program can choose whether or not to treat this as being an integer or a string. The digit stored
as the first character in the string stored in an element of the array is, of course, a character.
The solution here is working with strings. The problem with strings is that you cannot
use a normal comparison. You cannot do a check like if (string 1 == string2).
The following code uses:
if (digit.equals(arrayDigit))
49
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
50
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
}
}
System.out.println("Enter candidate to get marks" );
Scanner myObj2 = new Scanner(System.in);
int numIn = myObj2.nextInt();
numIn--;
System.out.println("exam 1 mark is " + examMarks[numIn][0]);
System.out.println("exam 2 mark is " + examMarks[numIn][1]);
}}
8.2 T
he following example shows how an array storing integer values could have all elements
in the array initialised with a value zero.
FOR rowCounter 0 TO lastRowIndex
FOR colCounter 0 TO lastColumnIndex
myArray[rowCounter, colCounter] = 0
NEXT colCounter
NEXT rowCounter
a The outer loop relates to values in a row and the inner loop to values in a column.
b The values for the variables lastRowIndex and lastColumnIndex must have been
assigned before the loop begins.
c If different values are to be assigned to different elements, there must be appropriate coding
inside the inner loop before the assignment statement supplying a value to an element.
This may require input from the user of the program.
End-of-chapter questions
1 a Program logic that can be used in many different applications.
b Likely examples are searching, sorting, counting, totalling, calculating an average value.
2 a Remember that the first index is 0, not 1. The values are 10 and 67.
b Pseudocode:
maxValue 0
FOR i 0 TO 2
51
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
FOR j 0 TO 4
IF testArray[i,j] > maxValue
THEN
maxValue testArray[i,j]
first i second j
ENDIF
NEXT j
NEXT i
OUTPUT "The highest value is " maxValue
OUTPUT "The row index is " first
OUTPUT "The column index is " second
3 Note that the headings shown in the table in the question are ignored in the design
and in the program code you provide for the following questions.
A pseudocode design:
DECLARE petType : ARRAY[0:3] OF STRING
DECLARE petColour : ARRAY[0:3] OF STRING
DECLARE petBreed : ARRAY[0:3] OF STRING
DECLARE choice : INTEGER
DECLARE petChoice : STRING
DECLARE list : STRING
list = ""
// The design will assume that these arrays are then
// populated with the values indicated in the question.
OUTPUT "Enter 1 to search for a pet type or 2 to search for
a pet of specific colour"
INPUT choice
IF choice = 1
THEN
OUTPUT "Enter a pet type"
INPUT petChoice
FOR i 0 TO 3
IF petType[i] = petChoice
THEN
list = list + " " + petColour[i]
+ " " + petBreed[i]
ENDIF
NEXT i
IF list <> ""
THEN
OUTPUT "The options are ", list
ELSE
OUTPUT "None found"
ENDIF
ENDIF
IF choice = 2
THEN
OUTPUT "Enter a pet type"
INPUT petChoice
52
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
4 import java.util.Scanner;
/*
linear search for pets
*/
class PetSearch {
public static void main(String[] args) {
String[] petType = new String[]{ "Cat", "Dog", "Dog", "Parrot"};
String[] petColour = new String[]{"White", "B & W", "Grey", "B & R"};
String[] petBreed = new String[] { "Persian", "Husky", "Poodle",
"Macaw"};
String choice, list, choice1;
list = "";
choice = "";
choice1 = "";
System.out.println
("Enter 1 to search for pet type; 2 to search also for colour");
Scanner myObj = new Scanner(System.in);
int searchValue = myObj.nextInt();
switch (searchValue)
{
case 1:
{
System.out.println("Enter a pet type");
Scanner myObj1 = new Scanner(System.in);
choice = myObj1.nextLine();
for ( int i = 0; i <= 3; i++)
{
if (petType[i].equals(choice))
list = list + " " + petColour[i] + " " + petBreed[i];
}
if (list.isEmpty())
System.out.println("None found");
53
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
else System.out.println(list);
}
break;
case 2:
{
System.out.println("Enter a pet type");
Scanner myObj2 = new Scanner(System.in);
choice = myObj2.nextLine();
5 Pseudocode design:
DECLARE pet : ARRAY[0:3, 0:2] OF STRING
DECLARE breedChoice : STRING
DECLARE petChoice : STRING
DECLARE choice : INTEGER
DECLARE list : STRING
list = ""
// The design will assume that the array is then populated
// with the values indicated in the question.
OUTPUT "Enter 1 to search for a pet type or 2 to search for
a pet of specific colour"
INPUT choice
IF choice = 1
THEN
OUTPUT "Enter a pet type"
INPUT petChoice
FOR i 0 TO 3
IF pet[i,0] = petChoice
THEN
list = list +" " pet[i,1] + " "
+ pet[i,2]
ENDIF
NEXT i
IF list <> ""
THEN
54
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
IF choice = 2
THEN
OUTPUT "Enter a pet type"
INPUT petChoice
OUTPUT "Enter a pet breed"
INPUT breedChoice
FOR i 0 TO 3
IF pet[i,0] = petChoice
AND pet[i,2] = breedChoice
THEN list = list +" " + pet[i,1]
ENDIF
NEXT i
IF list <> ""
THEN
OUTPUT "The options are " list
ELSE
OUTPUT "None found"
ENDIF
ENDIF
Java code:
import java.util.Scanner;
/*
linear search for pets
*/
class PetSearch2D {
public static void main(String[] args) {
String[][] pet = new String[][]{
{"Cat", "White", "Persian"},
{"Dog", "Black & White", "Husky"},
{"Dog", "Grey", "Poodle"},
{"Parrot", "Blue & Red", "Macaw"}
};
switch (searchValue)
55
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
{
case 1:
{
System.out.println("Enter a pet type");
Scanner myObj1 = new Scanner(System.in);
choice = myObj1.nextLine();
for ( int i = 0; i <= 2; i++)
{
if (pet[i][0].equals(choice))
list = list + " " + pet[i][1] + " " + pet[i][2];
}
if (list.isEmpty())
System.out.println("None found");
else System.out.println(list);
}
break;
case 2:
{
System.out.println("Enter a pet type");
Scanner myObj2 = new Scanner(System.in);
choice = myObj2.nextLine();
System.out.println("Enter a pet colour");
Scanner myObj3 = new Scanner(System.in);
choice1 = myObj3.nextLine();
for ( int i = 0; i <= 2; i++)
{
if ((pet[i][0].equals(choice)) && (pet[i][1].equals(choice1)))
list = list + " " + pet[i][2];
}
if (list.isEmpty())
System.out.println("None found");
else System.out.println(list);
}
}
}}
56
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Create a catalogue
* * *
lnitialise Input book Store book
variables details details
This could be expanded. For example, it could include boxes for input book title, input book
author and input book number of pages. However, it is normally best to leave that level of detail
for a pseudocode or flowchart design. It can be noted that this diagram only relates to the creation
of the catalogue. A full system design would need to include details of the use of the catalogue.
Pseudocode design:
DECLARE bookTitle: STRING
DECLARE bookAuthor: STRING
DECLARE bookNumPages: INTEGER
bookTitle ""
bookAuthor ""
bookNumPages 0
WHILE bookNumPages >= 0 DO
INPUT bookNumPages
IF bookNumPages > 0
THEN
INPUT bookTitle
INPUT bookAuthor
ENDIF
ENDWHILE
STORE book details
This design is incomplete. There is no definition of how the values are initially stored in the
program after the data has been input. The last line of this pseudocode does not follow the syntax
usually seen. It is the best that can be done in the absence of any details being provided for how
the system is going to store the data. During the loop, the book data would be entered into an
array or arrays. When input had finished, the content of the array or arrays would be stored in
one process. This storage would ensure that the data was available for future use.
57
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
Declare and
initialise variables
INPUT bookNumPages
FALSE
STOP
• The style of the meal (e.g. formal meal with waiting staff or buffet where attendees
help themselves to items).
58
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
9.3 There are several ways that this might be tackled. The following is one possibility.
Arrange
catering
Store
Receive Confirm Store contract Contact
arrangements
request contract details details supplier
for delivery
Challenge tasks
9.1 This design assumes that, when a weather station sends in their monthly figures, this is all the
data that they have. If the data for some of the days is missing, this is because no measurements
were taken. The proposed system will estimate values for the missing days.
Collect
rainfall
data
* Output monthly
Use data Estimate Output for average
as sent missing data each station for the country
59
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
• Customer details.
• Aircraft to be used.
• Names of pilots.
Charter flight
60
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
End-of-chapter questions
1
Weather app
Output the
Input location
forecast
2 It is worth noting how a system like this would be used. The intention would be for everything
that the receptionist deals with to be logged in the system. For example, if a patient calls the
centre, the receptionist might have to give an answer to a query. Alternatively, the receptionist
might have to book an appointment with a nurse or a doctor. Whatever action the receptionist
takes, there must be some details of this action entered into the system.
Book a service
Handle patient Book appoinment
provided
interaction in health centre
elsewhere
Book Book
Deal with Contact appointment appointment Book Book hospital
phone call patient with nurse with doctor ambulance appointment
61
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
System.out.println("Enter a password");
Scanner myObj = new Scanner(System.in);
String password = myObj.nextLine();
lengthPW = password.length();
if (lengthPW < 6)
System.out.println("password should be 6+ characters");
else PWlengthGood = true;
}
System.out.println("password acceptable");
}}
10.2 This fragment leaves a value for the variable dayNumber that can be used for whatever
purpose in subsequent coding added to the code here.
import java.util.Scanner;
/*
check if 1 - 31
*/
class MonthDay{
public static void main(String[] args) {
boolean dayInRange = false;
int dayNumber = 0;
while (dayInRange == false)
{
System.out.println("Enter a number for the day in the month");
Scanner myObj = new Scanner(System.in);
dayNumber = myObj.nextInt();
if (dayNumber >= 1 && dayNumber <= 31) dayInRange = true;
else System.out.println
("number should be in the range 1 - 31");
}
}}
62
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
63
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
}
System.out.println("Integer entered is " + intVal);
}}
Challenge tasks
10.1 T
his code does a check that a correct name has been input for the month (with an upper case
first letter). It checks for a leap year in a simple way just by asking the user to confirm this.
There is a final output just to indicate that inputs have been accepted. Further code could be
substituted for this last line. The code at present just confirms that sensible values have been
input for the month and the day number in the month.
import java.util.Scanner;
/*
check if value matches number possible for a specific month
*/
class MonthDayImproved{
public static void main(String[] args) {
64
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
problemFound = true;
System.out.println("Enter day number");
while (problemFound)
{
Scanner myObj2 = new Scanner(System.in);
dayNumInput = myObj2.nextInt();
problemFound = false;
if (dayNumInput < 1 || dayNumInput > numberInMonth)
65
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
{
System.out.println("number wrong, please try again");
problemFound = true;
}
}
System.out.println("OK");
}}
End-of-chapter questions
1 A test of length would normally be applied to a string. The test is only concerned with the
number of characters; it does not matter which characters are in the string.
A range check is only concerned with the value input. The value must not be too small and
it must not be too large.
2 Verification is about checking that what has been input is what was intended to be input.
1 Double entry is where the user is asked to repeat the input. This is then accepted if
the two inputs are identical.
2 In a visual check, the user is requested to read what has been input. The system might
display what has just been input with a request for it to be checked. If the user finds a
problem then the input can be repeated.
3 Some verification concerns checking the identity of the user. The question is not about
the data input but rather about who is entering the data. In this case some supporting
input is requested from the user. For example, “What is the name of your first pet?”
3 Note that the function returns a value false as soon as a problem is found.
static boolean nameAndPWcheck(String name, String PW)
{
boolean check = true;
int i = -1;
while (check && (i <= (name.length() - 2)))
{
i = i + 1;
if (!(Character.isLowerCase(name.charAt(i)) ||
(name.substring(i, i + 1).equals("-"))))
{
check = false;
return check;
}
}
if (!(PW.substring(0,1).equals("P")))
{
check = false;
return check;
}
if (PW.length() != 7)
{
66
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
check = false;
return check;
}
for (int j = 1; j <= 6; j++)
{
if (!(Character.isDigit(PW.charAt(j))))
{
check = false;
return check;
}
}
return check;
}
67
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
It should be noted that the program contains no coding that limits the acceptable temperature
range. However, a temperature value of 100 °C would be impossible and would be rejected
in a properly coded program. For the month number, a value of 15 would be abnormal and
would cause the program to fail. It can also be noted that a negative value input for the month
number would be accepted.
For boundary data, month numbers of 11 and 12 would be sensible. For temperature, the
program should really have a decision made about the possible temperatures for a location.
However, because the program includes a value of −25 then sensible boundary data values
would be −25 and −24.
Assuming that you enter positive numbers you will get output 0. If you are looking to find
a minimum value, you need to code a high value for the initialisation of minimumValue.
It is easy to forget this.
68
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
The answer is incorrect because the code does not allow the value of x = 15 to be divided
one more time. The code:
WHILE x > y DO
should be:
WHILE x >= y DO
It is often important to carry out a dry-run more than once. This particular code is a simple
example that illustrates that a successful dry-run does not guarantee that the code is correct.
For any sizeable program, it is very difficult, if not impossible, to be sure that logic errors
have all been removed.
Challenge tasks
11.1 1 For this program there are four values input initially. None of these are going to change
so it makes sense not to include them in the trace table.
For this first dry-run we input:
• length 6 m
• width 5 m
• coverage for one tin 7 m2
• number of coats 2.
69
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
3 The second dry-run indicates a major problem that when one tin should be sufficient then
the code may provide a value of zero. This could be corrected by the program checking for a
value of zero for the number of tins and outputting 1 instead of 0.
However, although the first dry-run has produced a non-zero output for the number of tins,
this is not necessarily a sensible value.
If the input values were changed to:
• length 6 m
• width 5 m
• coverage for one tin 8 m2
• number of coats 2
the dry-run would produce:
Now let’s consider that the design is changed to the following for the calculation.
area = area *
numberCoats
70
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
If the number of tins bought was based on the first design, there would not be enough. However,
the algorithm is still faulty because the number of tins calculated using an integer division leaves
some of the area being ignored. The number calculated should be increased by 1 to ensure that the
painter has enough paint.
End-of-chapter questions
1 a A syntax error.
b A runtime error.
c A logic error.
b When you test with normal values, you are hoping that your program has the correct
logic. In such a test, an expected outcome should have been defined when the test plan was
designed.
Abnormal data can be any type of data or any value that the program has not been designed
and created to handle. A well-written program will reject such data when there is an attempt
to enter it.
Extreme data is chosen to have values which are on the limit of those that the program can
handle. As with normal data, there should be an expected outcome when such data is input.
Testing with boundary data involves using a value which is an example of extreme data and
then using a value which is just beyond the acceptable limit. Sometimes, a range of values is
acceptable, in which case the boundary data should test the lower and the higher limits of
this range.
71
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
3 The most important feature of a debugger is the capability to proceed one step at a time in the
execution of a program.
The next most important feature is the capability to display the values stored for variables
at each stage of the execution.
Breakpoints can be defined. A breakpoint identifies a line in your code. You should be
able to jump forward to the next breakpoint with code being executed along the way.
It should be possible to change the values stored for variables to investigate the effect on
subsequent execution.
class GuessingGame {
public static void main(String[] args) {
int randNum = 0;
int score1 = 0;
int score2 = 0;
int max1 = 0;
int max2 = 0;
int total1 = 0;
int total2 = 0;
// the outer loop
for (int j = 1; j <= 2; j++)
{
if (j == 1)
System.out.println("First player please");
else
System.out.println("Second player please");
72
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
73
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
}
else if (total2 > total2)
{
System.out.println("Player 2 wins");
noWinner = false;
}
}
if (noWinner) System.out.println("The game is drawn");
}}
2 /*
Only a code fragment is expected
Some extra arrays are needed
Two lines of code have been used for each array declaration
You might have chosen to combine these into single line versions
Using double is easier than using float
*/
double[] healthIndex;
healthIndex = new double[sampleSize];
String[] rating;
rating = new String[sampleSize];
double totalHI = 0.0;
double averageHealthIndex = 0.0;
int totalRed = 0;
int totalOrange = 0;
int totalGreen = 0;
//Only a single loop is needed even though there is a 2D array
//It is important to use the correct order for the index values
for (int i = 0; i < sampleSize; i++)
{
healthIndex[i] = nutrition[0][i] + nutrition[1][i] * 2 + nutrition[3]
[i] * 100;
totalHI = totalHI + healthIndex[i];
if (i == sampleSize - 1)
averageHealthIndex = round(totalHI / sampleSize);
//The above calculates the average only in the final iteration
74
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
totalGreen = totalGreen + 1;
}
//There is an explanation included in each output statement
System.out.println("For " + snackName[i] + " values are:");
System.out.println
("Percent carbohydrates = " + round(nutrition[0][i]));
System.out.println
("The health index = " + healthIndex[i]);
System.out.println("Rating = " + rating[i]);
}
System.out.println
("The average value of all of the health indexes = " +
averageHealthIndex);
System.out.println("Number of Red = " + totalRed);
System.out.println("Number of Orange = " + totalOrange);
System.out.println("Number of Green = " + totalGreen);
3 This has been presented as a complete program here. In practice, the bank’s system would
have the code created as a subroutine. Full marks could be awarded without the three lines
of header code.
import java.util.Scanner;
class checkID {
public static void main(String[] args) {
String customerID = "";
int len;
boolean IDneeded = true;
int attempts = 0;
/*
The above two statements combined with the loop condition ensure that
the loop that follows is entered at least once
If a correct version of the customerID is entered at the first
attempt the loop is only entered once
*/
while (IDneeded && attempts < 3)
{
attempts = attempts + 1;
System.out.println("Please enter customerID");
Scanner myObj = new Scanner(System.in);
customerID = myObj.nextLine();
/*
The following code checks individual requirements individually,
one at a time, in a sensible order
The program only continues checking when no error is found
*/
len = customerID.length();
if (len != 6)
System.out.println("must be 6 characters");
else
{
boolean lowercase = true;
75
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
char lower;
for (int i = 0; i <= 3; i++)
{
lower = customerID.charAt(i);
if (lower < 'a' || lower > 'z') lowercase = false;
}
if (!lowercase)
System.out.println("lower case needed");
else
{
boolean numDigit = true;
char num;
for (int j = 4; j <= 5; j++)
{
num = customerID.charAt(j);
if (num < '1' || num > '9') numDigit = false;
}
if (!numDigit)
System.out.println("numeric digits needed");
else IDneeded = false;
}
}
}
if (IDneeded)
System.out.println("No more attempts allowed");
else System.out.println("customerID accepted");
}}
76
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
77
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
averageDistance[ij] = 0.0;
bestDistance[ij] = -20.0;
category[ij] = "";
}
double distanceCovered;
78
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
INTEGER counter ← 0
STRING vote ← ""
INTEGER Faraday ← 0
INTEGER Curie ← 0
REAL percent ← 0
INPUT
vote
TRUE FALSE
Faraday ← vote = Curie ←
Faraday + 1 "Faraday" Curie + 1
counter ←
counter + 1
FALSE
counter = 601
TRUE
TRUE FALSE
percent ← Faraday > percent ←
100.0*Faraday/601 Curie 100.0*Curie/601
OUTPUT OUTPUT
"Winner is Faraday "Winner is Curie
with" + percent + "%" with" + percent + "%"
STOP
79
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
One mark for each correct identification of error, One mark for appropriate solution to error.
• Low is declared as 0 / Low will always be lowest value / Low 0.
• Initialise Low to a value > 200 / Set Low to be the first mark input / Low 201.
80
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
• The check digit is the result of Modulus division of Total by 10 (accept 11).
• When the number is input, the calculation is performed again
• If the calculated value does not match check digit input, error has occured.
b Maximum of two marks from one for each correct validation {cao (correct answer only)}.
c Maximum of three marks from one for each correct data value:
Note:
Look out for missing initialisation zeros – penalise once and then ignore.
Can accept repeated values in a column.
Accept only one output value (reject multiple values even if final value correct).
81
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Example flowchart:
START
username ← ""
counter = 0
INPUT
username
username = TRUE
OUTPUT
netName(counter) counter
FALSE
STOP
counter ←
counter + 1
82
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Example pseudocode (this is an example; any working solution will gain marks):
DECLARE username : STRING
DECLARE counter : INTEGER
DECLARE found : BOOLEAN
DECLARE netName : ARRAY[0:599] OF STRING
username ""
counter 0
found FALSE
INPUT username
WHILE Counter < 599 AND Found = FALSE
IF username = netName(counter)
THEN
OUTPUT counter
found TRUE
ENDIF
ENDWHILE
IF found = FALSE
THEN
OUTPUT "NO Record"
ENDIF
Example pseudocode:
FOR Counter1 = 0 TO 8
FOR Counter2 = 0 TO 8
Board (Counter1, Counter2) "Free"
NEXT Counter2
NEXT Counter1
83
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
prodNum ←""
INT Length ← 0
INPUT
prodNum
TRUE
length
<> 10
FALSE
STOP
Example pseudocode:
STRING prodNum ""
INPUT prodNum
IF LENGTH (prodNum) <> 10
THEN
OUTPUT "Rejected"
ELSE
IF SUBSTRING (prodNum, 1, 4) <> "PROD"
THEN
OUTPUT "Rejected"
ENDIF
ELSE
OUTPUT "Accepted"
ENDIF
84
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Example pseudocode:
FUNCTION convert(tempCelsius: REAL) RETURNS REAL
DECLARE tempFahrenheit : REAL
tempFahrenheit tempCelsius * 1.8) + 32
RETURN tempFahrenheit
ENDFUNCTION
b Maximum of six marks from one for each correct data type:
85
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
INPUT age
TRUE
classification
age < 10
← "child"
FALSE
TRUE
classification
age < 18
← "junior"
FALSE
TRUE
classification
age < 60
← "adult"
FALSE
classification
← "senior"
STOP
A name (one mark) used in a program to identify a memory location (one mark).
86
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Once written, the subroutine can be used many times without the need for the
code to be written again.
i milesToKm
ii CALL milesToKm(milesDistance)
87
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
a newString UCASE(oldString)
b newString SUBSTRING(oldString, 8, 1)
c newString SUBSTRING(oldString, 1, 1)
d newString SUBSTRING(oldString, 5, 4)
a newString = oldString.toUpperCase();
b newString = oldString.Substring(7);
c newString = oldString.Substring(0,1);
d newString = oldString.Substring(4);
Membership
application decision
Receive
Receive details Send decision
supporting Store decision
of applicant to applicant
details
Sorry
Welcome to application
membership rejected
88
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
16 Maximum of six marks: one mark for a then one each for any from b. Maximum five marks if no
example code included in the answer.
Example answer:
FUNCTION CalcAverage
(T1: INTEGER, T2: INTEGER, T3: INTEGER,
T4: INTEGER, T5: INTEGER) RETURNS INTEGER
TotalMinutes T1 + T2 + T3 + T4 + T5
Average ROUND(TotalMinutes / 5)
RETURN Average
ENDFUNCTION
INPUT FirstName
INPUT LastName
89
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
CASE OF Counter
1 : INPUT Time1
2 : INPUT Time2
3 : INPUT Time3
4 : INPUT Time4
5 : INPUT Time5
ENDCASE
NEXT Counter
AverageMinutes CalcAverage
(Time1, Time2, Time3, Time4, Time5)
OUTPUT Firstname , " " , Lastname
, " Average marathon time:"
OUTPUT (AverageMinutes DIV 60) , "hrs "
, (AverageMinutes MOD 60) , "mins"
Example answer:
INPUT FirstName
INPUT LastName
TotalMinutes 0
FOR Counter 1 TO 5
INPUT MarathonTime
TotalMinutes TotalMinutes + MarathonTime
NEXT Counter
AverageMinutes TotalMinutes / 5.0
OUTPUT Firstname , " " , Lastname
, " average marathon time:"
OUTPUT (AverageMinutes DIV 60) , "hrs " ,
(Average_minutes MOD 60) , "mins"
One mark for: Local variables can be only be accessed in the subroutine / function /
procedure where they are declared.
90
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
d Maximum of two marks from the following, one mark for each point with reason:
• It is possible to accidentally use an identifier twice without noticing, whereas local
variable names can be used elsewhere in the program.
• It is possible that the value can be accidentally changed by other code in the program.
• It can make testing harder as the variable could be changed anywhere in the program.
• It can make maintenance harder as the variable could be changed anywhere in the
program.
91
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Example answer:
import static java.lang.String.*;
import java.util.Scanner;
import java.util.Random;
class Q20 {
public static void main(String[] args) {
System.out.println("Please enter your first name");
Scanner myObj1 = new Scanner(System.in);
String firstName = myObj1.nextLine();
System.out.println("Please enter your last name");
Scanner myObj2 = new Scanner(System.in);
String lastName = myObj2.nextLine();
int len = lastName.length();
String lowerName1 = firstName.toLowerCase();
String lowerName2 = lastName.toLowerCase();
String name1 = lowerName1.substring(0,2);
String name2 = lowerName2.substring(len - 5);
String userName = name1 + name2;
92
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
c Three marks, one mark per line; maximum of two marks if two temporary reads made:
Temp Map[2,2]
Map[2,2] Map[4,4]
Map[4,4] Temp
93