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

igcse_compsci_2ed_java_sol

The document is a programming book for Cambridge IGCSE™ & O Level Computer Science, focusing on Java and algorithms. It includes sample answers, end-of-chapter questions, and practice tasks related to programming concepts such as variables, arithmetic operators, and pseudocode. The content emphasizes the importance of correct identifier usage in pseudocode and provides various algorithm designs for grading and calculations.
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)
44 views

igcse_compsci_2ed_java_sol

The document is a programming book for Cambridge IGCSE™ & O Level Computer Science, focusing on Java and algorithms. It includes sample answers, end-of-chapter questions, and practice tasks related to programming concepts such as variables, arithmetic operators, and pseudocode. The content emphasizes the importance of correct identifier usage in pseudocode and provides various algorithm designs for grading and calculations.
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/ 93

CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

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.

2.2 An identifier or name or both to match the grade.

A possible revised Algorithm 2 could be:

Input total mark possible

Input candidate identifier

Input candidate mark

Calculate percentage

Grade as Distinction if percentage above 80

Grade as Merit if percentage in range 61–80

1
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Grade as Pass if percentage in range 40–60

Grade as Fail if percentage less than 40

Look up candidate name

Output candidate name and grade

2.3 Input total mark possible

Do the following for each candidate:

Input candidate mark

Calculate percentage

Grade as Distinction if percentage above 80

Grade as Merit if percentage in range 61–80

Grade as Pass if percentage in range 40–60

Grade as Fail if percentage less than 40

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 total mark


for each exam

Input identifier

Input mark for


each exam

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.

iv Selection: A logic construct in which alternative actions are possible in an algorithm


and the choice of which action is performed is defined by a condition.

v Iteration: A logic construct in which a sequence of actions in an algorithm is


repeated several times.

2
Either input or output

Any action, such as an assignment statement


or a process. It could include several of these
inside one symbol.

A statement or expression that can be tested


to see if it is true or false.

5
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

3
START

Set total to zero

Input item price

Input number
bought

Calculate price for


this number of items

Add to total

Any more items?


TRUE

FALSE

Output total
price to pay

STOP

Chapter 3: Variables and arithmetic operators


There are several examples of solutions provided here which use Java code. In several cases
the code uses integer literals when an alternative solution using a float literal would be possible.
Integer literals have been used because float literals need special treatment in Java.
You will be given details of this in Section 4.7 in Chapter 4.

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

The question to be decided about age is how accurately it needs to be recorded.


The age might be stored as a single variable named ageLastBirthday of type integer.
Another option would be to record the date of birth and use a calculation to find the age.

Recording the number of years and the number of months would fit most purposes.

The declaration statements could be:


String givenName, familyName ;
int yearsOld, monthsOld;

3.2 INPUT number1


INPUT number2
answer  number1 * number2
OUTPUT answer

The Java code for declarations and calculation is:


float number1, number2, answer;
answer = number1 * number2;

Note that using integer values is an alternative but the program would not be as useful.

3.3 The flowchart is:

START

Input length
Input width
Input depth

volume ← length * width * depth

volume ← volume / 1000

Output volume

STOP

7
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

The Java code for declaration and calculation is:


float length, width, depth, volume;
volume = length * width * depth;
volume = volume/1000;

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

lawnArea ← lawnLength * lawnWidth


seedNeeded ← lawnArea * seedCoverage / 1000
seedNeededCost ← seedNeeded * 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

3.5 a The identifier table:

Variable Type Explanation of use


standardSingleFare float will need to be looked up from stored values
ticketPrice float to be calculated for one journey for one person
totalPrice float the total for one booking
discountForReturn float a fractional value stored as a constant
discountForChild float a fractional value stored as a constant
discountAdvance float a fractional value stored as a constant
departureStation String will be input
arrivalStation String will be input
numberOfTickets int will be input
age int will be input
singleTicket boolean if false will indicate that a return ticket is needed
advanceBooking boolean true if for 6+ tickets one month or more in advance
dateOfBooking String might use Java provided features
dateOfTravel String might use Java provided features

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

One possible single assignment statement would be:

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.

3.2 The identifier table:

Variable Type Explanation of use


numberOfBags int to be calculated from the amount of grain and the bag capacity
bagCapacity int to be stored as a constant
bagPrice int to be input
amountOfGrain int to be input
totalPrice int to be calculated from the number of bags and the bag price

Pseudocode design:
CONSTANT bagCapacity  25
INPUT bagPrice
INPUT amountOfGrain
amountOfGrain  amountOfGrain * 95 / 100
numberOfBags  amountOfGrain / bagCapacity
totalPrice  numberOfBags * bagPrice
OUTPUT numberOfBags
OUTPUT totalPrice

Note that this design uses integer division.

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.

Java code for declarations and calculations:


final int bagCapacity = 25;
int bagPrice, amountOfGrain, numberOfBags, totalPrice;

10
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

amountOfGrain = amountOfGrain * 95 / 100;


numberOfBags = amountOfGrain / bagCapacity;
totalPrice = numberOfBags * bagPrice;

Note that the assignment statements could be merged into one if you wished.

3.3 Identifier table:

Variable Type Explanation of use


poolVolume int will be input
drainageRate int will be input
minutesToDrain int to be calculated initially from the input values
hoursToDrain int to be calculated from minutesToDrain using integer division
minutes int needed for calculating the number of minutes after the number
of hours has been calculated

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.)

Java code for declarations and calculations:


int poolVolume, drainageRate;
int minutesToDrain, hoursToDrain, minutes;
minutesToDrain = poolVolume / drainageRate;
hoursToDrain = minutesToDrain / 60;
minutes = hoursToDrain * 60;
minutesToDrain = minutesToDrain – minutes;

3.4 Identifier table:

Variable Type Explanation of use


lengthOfWall int to be input
heightOfWall int to be input
numberOfCoats int to be input
areaToPaint int to be calculated
tinCoverage int to be input
numberOfTins int to be calculated

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

Java for declaration statements and for calculations.


int lengthOfWall, heightOfWall, areaToPaint;
int numberOfCoats, tinCoverage, numberOfTins;
areaToPaint = lengthOfWall * heightOfWall * numberOfCoats;
numberOfTins = areaToPaint / tinCoverage;
numberOfTins = numberOfTins + 1;

Skills focus questions


3.1 1 The first two assignment statements are easily combined:
timeForTravel =
(distance1 + distance2 + distance3)/averageSpeed

+ timeForBreak * 2;

Now one option for the combined statement is:


timeForTravel = 1.1 * timeForBreak * 2 + 1.1 *
(distance1 + distance2 + distance3) / averageSpeed;

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.

b When multiplication or addition produced a value too large to store (overflow).

c A different data type is provided which allocates a larger number of bits.

2 Pseudocode:

percentageMark  candidateMark * 100 / totalMarkPossible

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:

Variable Type Explanation of use


hourlyRate float to be input; applies to normal working hours
overtimeRate float to be input; expected to be different to the hourly rate
normalHoursWorked int to be input
overtimeHoursWorked int to be input
grossPay float to be calculated
taxRate float to be input as a percentage
amountToBePaid float to be calculated and output

4 INPUT distanceOfJourney
INPUT fixedCost
INPUT extraCostPerMile
totalCharge  fixedCost + (distanceOfJourney – 2) * extraCostPerMile
OUTPUT totalCharge

13
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Chapter 4: Options when learning programming


Practice tasks
4.1 class Hello {
public static void main(String [] args) {
System.out.println("Hello");
}}

4.2 import java.util.Scanner;


/*
calculates sum and average
*/
class FloatTest1 {
public static void main(String[] args) {

float sum = 0.0;


System.out.println("Please enter a number");
Scanner mynum = new Scanner(System.in);
float number1 = mynum.nextFloat();
sum = 10.0 + number1;
System.out.println("The sum of your number and 10 is " + sum);

}}

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

System.out.println("The sum of your number and 10 is " + sum);


}}
import java.util.Scanner;
/*
calculates sum and average
*/
class FloatTest3 {
public static void main(String[] args) {
double sum = 0.0;
System.out.println("Please enter a number");
Scanner mynum = new Scanner(System.in);
double number1 = mynum.nextFloat();
sum = 10.0 + number1;
System.out.println("The sum of your number and 10 is " + sum);
}}

4.3 import java.util.Scanner;


/*
to illustrate input of a string and of an integer
*/
class InputProg {
public static void main(String[] args) {
int num,sum;
num = 10;
sum = 0;
System.out.println("What is your name");
Scanner nameInput = new Scanner(System.in);
String yourName = nameInput.nextLine();
System.out.println("Hello " + yourName);
System.out.println(
"Please enter a number between 1 and 10");
// the program will fail
// if an integer is not entered
Scanner numberInput = new Scanner(System.in);
int yourNumber = numberInput.nextInt();
sum = num + yourNumber;
System.out.println("Your number plus 10 = " + sum);
}}

15
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

4.4 import java.util.Scanner;


/*
to illustrate arithmetic
*/
class MultMachine {
public static void main(String[] args) {
float number1, number2, answer;
System.out.println("Enter first number");
Scanner number1Input = new Scanner(System.in);
number1 = number1Input.nextFloat();
System.out.println("Enter second number");
Scanner number2Input = new Scanner(System.in);
number2 = number2Input.nextFloat();
answer = number1 * number2;
System.out.println("multiplication gives " + answer);
}}

4.5 import java.util.Scanner;


/*
to illustrate arithmetic
*/
class AquariumVol {
public static void main(String[] args) {
float length, width, depth, volume;
System.out.println("Enter length");
Scanner number1Input = new Scanner(System.in);
length = number1Input.nextFloat();
System.out.println("Enter width");
Scanner number2Input = new Scanner(System.in);
width = number2Input.nextFloat();
System.out.println("Enter depth");
Scanner number3Input = new Scanner(System.in);
depth = number3Input.nextFloat();
volume = length * width * depth;
volume = volume/1000;
System.out.println("The volume is " + volume);
}}

4.6 import java.util.Scanner;


/*
to illustrate arithmetic
*/
class LawnSeed {
public static void main(String[] args) {
final float seedCoverage = 50.0f;
float lawnLength, lawnWidth, lawnArea;
float seedPrice, seedNeeded, seedNeededCost;
System.out.println("Enter lawn length");
Scanner number1Input = new Scanner(System.in);
lawnLength = number1Input.nextFloat();
System.out.println("Enter lawn width");

16
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Scanner number2Input = new Scanner(System.in);


lawnWidth = number2Input.nextFloat();
System.out.println("Enter seed price");
Scanner number3Input = new Scanner(System.in);
seedPrice = number3Input.nextFloat();
lawnArea = lawnLength * lawnWidth;
seedNeeded = lawnArea * seedCoverage / 1000;
seedNeededCost = seedNeeded * seedPrice;
System.out.println("You need this many kg of seed " + seedNeeded);
System.out.println("It will cost you $" + seedNeededCost);
}}

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;

System.out.println("Enter price to be charged for a bag");


Scanner number1Input = new Scanner(System.in);
bagPrice = number1Input.nextInt();
System.out.println("Enter amount of grain harvested");
Scanner number2Input = new Scanner(System.in);
amountOfGrain = number2Input.nextInt();

amountOfGrain = amountOfGrain * 95 / 100;


numberOfBags = amountOfGrain / bagCapacity;
totalPrice = numberOfBags * bagPrice;

System.out.println("Number of bags is " + numberOfBags);


System.out.println("Total price for these is $" + totalPrice);
}}

4.2 import java.util.Scanner;


/*
to illustrate arithmetic
*/
class PoolDraining {
public static void main(String[] args) {
int poolVolume, drainageRate;
int minutesToDrain, hoursToDrain, minutes;

System.out.println("Enter pool volume");


Scanner number1Input = new Scanner(System.in);
poolVolume = number1Input.nextInt();

17
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

System.out.println("Enter drainage rate");


Scanner number2Input = new Scanner(System.in);
drainageRate = number2Input.nextInt();

minutesToDrain = poolVolume / drainageRate;


hoursToDrain = minutesToDrain / 60;
minutes = hoursToDrain * 60;
minutesToDrain = minutesToDrain - minutes;
System.out.println("The time to drain is " + hoursToDrain + " hours
and " + minutesToDrain + " minutes");
}}

4.3 import java.util.Scanner;


/*
to illustrate arithmetic
*/
class TinsOfPaint {
public static void main(String[] args) {

int lengthOfWall, heightOfWall, areaToPaint;


int numberOfCoats, tinCoverage, numberOfTins;

System.out.println("Enter the length of the wall");


Scanner number1Input = new Scanner(System.in);
lengthOfWall = number1Input.nextInt();
System.out.println("Enter the height of the wall");
Scanner number2Input = new Scanner(System.in);
heightOfWall = number2Input.nextInt();
System.out.println("Enter the number of coats needed");
Scanner number3Input = new Scanner(System.in);
numberOfCoats = number3Input.nextInt();
System.out.println("Enter the coverage provided by one tin");
Scanner number4Input = new Scanner(System.in);
tinCoverage = number4Input.nextInt();

areaToPaint = lengthOfWall * heightOfWall * numberOfCoats;


numberOfTins = areaToPaint / tinCoverage;
numberOfTins = numberOfTins + 1;

System.out.println("The number of tins needed is " +


numberOfTins);
}}

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) {

float costOfBulk, costForFarmer;


int numberOfFarmers;

System.out.println("Enter cost of bulk buy");


Scanner number1Input = new Scanner(System.in);
costOfBulk = number1Input.nextFloat();
System.out.println("Enter the number of farmers");
Scanner number2Input = new Scanner(System.in);
numberOfFarmers = number2Input.nextInt();

costOfBulk = costOfBulk + costOfBulk * 0.1f;


costForFarmer = costOfBulk / numberOfFarmers;
System.out.println("Cost for each farmer is $" + costForFarmer);
}}

19
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Chapter 5: Selection
Practice tasks
5.1 Rule 1

a int age;
boolean withParent;

b age < 5 && 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;

b student && withStudentCard

Rule 3

a boolean seasonTicket;
String travelDate, expiryDate;

b seasonTicket && travelDate <= expiryDate

5.2 import java.util.Scanner;


/*
pass or fail
*/
class PassOrFail {
public static void main(String[] args) {
int percent;
boolean pass;
System.out.println("Enter percent");
Scanner number1Input = new Scanner(System.in);
percent = number1Input.nextInt();
if (percent >= 40) {
System.out.println("Pass");}
else{
System.out.println("Fail");}
}}

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

percent > 80? grade ← "Distinction"

FALSE

TRUE

percent > 60? grade ← "Merit"

FALSE

TRUE

percent >= 40? grade ← "Pass"

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

percent > 80? grade ← "Distinction"

FALSE

TRUE
percent > 60? grade ← "Merit"

FALSE

TRUE

percent >= 40? grade ← "Pass"

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

else if (percent >= 40)


grade = "Pass";
System.out.println("The grade is " + grade);
}}

5.6 import java.util.Scanner;


/*
to calculate the ticket price for a destination station
*/
class TicketMachine {
public static void main(String[] args) {

final int station1Price = 10;


final int station2Price = 15;
final int station3Price = 20;
final int station4Price = 25;

int stationNumber = 0;
int priceToPay = 0;

System.out.println("Enter number code for destination station ");


Scanner number1Input = new Scanner(System.in);
stationNumber = number1Input.nextInt();

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) {

final int standardPrice = 50;


int age = 0;
int ticketNumber = 0;
int category = 0;
double priceToPay = 0.0;

System.out.println("Enter age");
Scanner number1Input = new Scanner(System.in);
age = number1Input.nextInt();

if (!(age < 5 || age >= 75) ){


System.out.println("Enter the number of tickets as 1 or 2");
Scanner numberInput = new Scanner(System.in);
ticketNumber = numberInput.nextInt();
}
if (age < 5 || age >= 75) category = 1;
else if ((age >= 5 && age <= 10) && ticketNumber == 1) category = 2;
else if ((age >= 5 && age <= 10) && ticketNumber == 2) category = 3;
else if (ticketNumber == 1) category = 4;
else category = 5;
switch (category)
{
case 1:
System.out.println("single or return free");
break;
case 2: {
priceToPay = standardPrice * 0.5;
System.out.println("Price for single is $" + priceToPay);
}
break;
case 3: {
priceToPay = standardPrice * 0.5;
System.out.println("Price for single is $" + priceToPay);
priceToPay = priceToPay * 0.2;
System.out.println("return price is $" + priceToPay);
}
break;
case 4: {
priceToPay = standardPrice;
System.out.println("Price for single is $" + priceToPay);
}

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);
}
}
}}

5.2 The following is a possible pseudocode design.


INPUT shape
INPUT cutOut
IF shape = "circle"
THEN
INPUT diameter
area  (diameter / 2) * (diameter / 2) * 3.14
IF cutOut = yes
THEN
areaCutOut  (diameter / 8) * (diameter / 8) *
3.14
area  area – areaCutOut
ENDIF
ELSE
IF shape = "square"
THEN
INPUT width
area  width * width
IF cutOut = yes
THEN
areaCutOut  width/8 * width/8 * 3.14
area  area – areaCutOut
ENDIF
ELSE
INPUT width
INPUT length
area  width * length
IF cutOut = yes
THEN
areaCutOut  width/8 * width/8 * 3.14
area  area – areaCutOut
ENDIF
ENDIF
INPUT seedCoverage
seedNeeded  area / seedCoverage
OUTPUT seedNeeded

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;

System.out.println("Enter shape of lawn");


System.out.println("1, 2 or 3 for circle, square or rectangle");
Scanner choiceInput = new Scanner(System.in);
lawnShape = choiceInput.nextInt();
System.out.println("Do you want a cut-out?");
System.out.println("Enter 1 if yes or 2 if no");
Scanner choice1Input = new Scanner(System.in);
choice = choice1Input.nextInt();
if (lawnShape == 1)
{
System.out.println("Enter the diameter");
Scanner number1Input = new Scanner(System.in);
diameter = number1Input.nextFloat();
area = 3.14 * diameter * diameter / 4;
if (choice == 1)
{
areaCutOut = 3.14 * 0.25 * diameter *
0.25 / 4;
area = area - areaCutOut;
}
}
else if (lawnShape == 2)
{
System.out.println("Enter the width");
Scanner number2Input = new Scanner(System.in);
width = number2Input.nextFloat();
area = width * width;
if (choice == 1)
{
areaCutOut = 3.14 * width * width / 4;
area = area - areaCutOut;
}
}
else if (lawnShape == 3)
{
System.out.println("Enter the width");
Scanner number3Input = new Scanner(System.in);
width = number3Input.nextFloat();

26
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

System.out.println("Enter the length");


Scanner number4Input = new Scanner(System.in);
length = number4Input.nextFloat();
area = width * length;
if (choice == 1)
{
areaCutOut = 3.14 * width * width / 4;
area = area - areaCutOut;
}
}

System.out.println("Enter the seed coverage");


Scanner number5Input = new Scanner(System.in);
seedCoverage = number5Input.nextFloat();

seedNeeded = area / seedCoverage;


System.out.println("seed needed is " + seedNeeded);

}}

Skills focus questions


5.1 1 This defines a range with the lowest value 61 and the highest value 81, which is incorrect.
2 This defines a range with the lowest value 61 and the highest value 80, which is correct.
3 This does not define a range. Any value from 81 upwards is accepted. The lowest value is
defined but not the highest.
4 This does not define a range. Any value from 61 upwards is accepted and at the same time
any value up to 80. There is no definition of a lowest value or of a highest value.
5.2 1 If four separate simple IF statements are used, then four tests will always be made. This is
wasteful. If, for example, the mark were greater than 80, there should be no need for further
checking. This is what happens by using the Option 1 code. It can also be argued that using
the IF ENDIF structure emphasises that the decisions are all related. It makes it easier to
check that all options have been included.
2 In an expression A AND B there is no need to check B if A is false. The nested IF option
starting with a single test emphasises this fact.
3 Yes. These conditions might be used if marks were categorised as either "Normal" or
as "Extreme". The following code could be used. In this case, the code emphasises that
if the first condition is true there is no need to test the second condition.
IF candidateMark < 40
THEN
category  "Extreme"
ELSE
IF candidateMark >= 80
THEN
category  "Extreme"
ENDIF

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 = "";

System.out.println("Enter percentage mark");


Scanner myObj = new Scanner(System.in);
candidateMark = myObj.nextInt();

if (candidateMark > 80)


grade = "Distinction";
else if (candidateMark > 60)
grade = "Merit";
else if (candidateMark >= 40)
grade = "Pass";
else grade = "Fail";

System.out.println("The grade is " + grade);


}}

End-of-chapter questions
1 ELSE
OUTPUT "the values are equal"
ENDIF

2 if (value1 > value2)


System.out.println("value1 is larger");
else if (value1 < value2)
System.out.println("value2 is larger");
else
System.out.println("the values are equal");

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

Scanner number4Input = new Scanner(System.in);


number3 = number4Input.nextInt();
if (number3 == number2 || number3 == number1)
{
System.out.println("duplicate, enter a different number");
Scanner number5Input = new Scanner(System.in);
number3 = number5Input.nextInt();}
if (number3 > maxValue) maxValue = number3;
System.out.println("The highest number is " + maxValue);
}}

4 D is false.

A is true together with either C is true or B 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);
}
}}

6.2 import java.util.Scanner;


/*
summing values
*/
class ValueSum {
public static void main(String[] args) {

30
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

System.out.println("Please enter the number of values");


Scanner numberInput = new Scanner(System.in);
int valuesNumber = numberInput.nextInt();
double total = 0.0;
double value = 0.0;
for (int i = 1; i <= valuesNumber; i++)
{
System.out.println("Please enter a real number");
Scanner realInput = new Scanner(System.in);
value = realInput.nextFloat();
total = total + value;
}
System.out.println("The total for the values is " + total);
}}

6.3 import java.util.Scanner;


/*
pass or fail for several candidates
*/
class MultiplePassOrFail {
public static void main(String[] args) {
int percent, numberOfValues;
System.out.println("Enter the number of candidates");
Scanner number1Input = new Scanner(System.in);
numberOfValues = number1Input.nextInt();
for (int i = 1; i <= numberOfValues; i++)
{
System.out.println("Enter percent");
Scanner number2Input = new Scanner(System.in);
percent = number2Input.nextInt();
if (percent >= 40) {
System.out.println("Pass");}
else{
System.out.println("Fail");}
}
}}

6.4 import java.util.Scanner;


/*
summing unknown number of values
*/
class Totalling{
public static void main(String[] args) {

double nextNumber = 0.0;


double total = 0.0;
while (nextNumber >= 0.0)
{
total = total + nextNumber;
System.out.println("Please enter a real number");
System.out.println("minus value stops program");

31
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Scanner realInput = new Scanner(System.in);


nextNumber = realInput.nextFloat();
}
System.out.println("The sum of the numbers is " + total);
}}

6.5 Pseudocode design Output


FOR i  1 TO 10 1 2 3 4 5 6 7 8 9 10
OUTPUT i
NEXT i
i  0 0123456789
WHILE i < 10
OUTPUT i
i  i + 1
ENDWHILE
i  0 1 2 3 4 5 6 7 8 9 10
WHILE i < 10
i  i + 1
OUTPUT i
ENDWHILE
i  0 0 1 2 3 4 5 6 7 8 9 10
WHILE i <= 10
OUTPUT i
i  i + 1
ENDWHILE
i  0 1 2 3 4 5 6 7 8 9 10 11
WHILE i <= 10
i  i + 1
OUTPUT i
ENDWHILE
i  1
WHILE i < 11
OUTPUT i
i  i + 1
ENDWHILE

32
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Challenge tasks
6.1
START

i←1
dTot ← 0
mTot ← 0
pTot ← 0
fTot ← 0

TRUE grade ← "Distinction"


percent > 80?
dTot ← dTot + 1

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

OUTPUT dTot, mTot


pTot, fTot

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 = "";

for (int i = 1; i <= 10; i++)


{
System.out.println("Enter percent");
Scanner numberInput = new Scanner(System.in);
percent = numberInput.nextInt();

if (percent > 80) {


grade = "Distinction";
dTotal = dTotal + 1;
System.out.println("The grade is " + grade);
}
else if (percent > 60) {
grade = "Merit";
mTotal = mTotal + 1;
System.out.println("The grade is " + grade);
}
else if (percent >= 40){
grade = "Pass";
pTotal = pTotal + 1;
System.out.println("The grade is " + grade);
}
else {
grade = "Fail";
fTotal = fTotal + 1;
System.out.println("The grade is " + grade);
}
}
System.out.println("The distinction number is " + dTotal);
System.out.println("The merit number is " + mTotal);
System.out.println("The pass number is " + pTotal);
System.out.println("The fail number is " + fTotal);
}}

6.2 import java.util.Scanner;


/*
to calculate the ticket price for more than one person
*/
class TicketManyPeople {
public static void main(String[] args) {
final int standardPrice = 50;
int age = 0;
int ticketNumber = 0;
int priceToPay = 0;
int totalPriceToPay = 0;
System.out.println("Enter age");
Scanner number1Input = new Scanner(System.in);
age = number1Input.nextInt();

34
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

while (age >= 0)


{
if (!(age < 5 || age >= 75))
{
System.out.println("Enter the number of tickets as 1 or 2");
Scanner numberInput = new Scanner(System.in);
ticketNumber = numberInput.nextInt();
}
int category = 0;

if ((age >= 5 && age <= 10) && ticketNumber == 1)


category = 1;
else if ((age >= 5 && age <= 10) && ticketNumber == 2)
category = 2;
else if (( age > 10 && age < 75 ) && ticketNumber == 1)
category = 3;
else if (( age > 10 && age < 75 ) && ticketNumber == 2)
category = 4;

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

Skills focus questions


6.1 1 
import java.util.Scanner;
/*
checking if a number is prime
*/
class PrimeTest {
public static void main(String[] args) {

int numberToBeTested = 0;
int i = 2;
boolean prime = true;
int theModulus = 0;

System.out.println("Enter integer below 100");


Scanner numberInput = new Scanner(System.in);
numberToBeTested = numberInput.nextInt();

while (i < (numberToBeTested - 1) && prime)


{
theModulus = numberToBeTested % i;
if (theModulus == 0) prime = false;
i = i + 1;
}
if (prime) System.out.println("The number is prime");
else System.out.println("The number is not prime");
}}
2 The following code fragment could be incorporated into a program:
int i = 1;
boolean correct = false;
correctNumber = 17;
while (!correct && i < 11)
{
System.out.println("Enter an integer below 26");
Scanner numberInput = new Scanner(System.in);
numberGuessed = numberInput.nextInt();
if (numberGuessed == correctNumber) correct = true;
i = i + 1;
}

if (correct) System.out.println("Correct guess, well done");


else System.out.println("Sorry, you failed to guess correctly");
The above code shows how a boolean variable could be used. The use of 17 for the correct value
which does not change if the program is used more than once is not sensible. In Chapter 7,
you will see how the program could be improved so that a different correct value is created each time
that the program is used.

36
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

End-of-chapter questions
1 a For loop, While loop, Do while loop

b for (int i = 1; i <= numberOfMultiples; i++)


while (nextNumber >= 0.0);
do {

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();

while ( !(aValue = 0.0))


{
if (aValue > maxValue) maxValue = aValue;
totalValue = totalValue + aValue;
numberOfValues = numberOfValues + 1;
System.out.println("Enter value");
Scanner numberInput = new Scanner(System.in);
aValue = numberInput.nextFloat();
}
average = totalValue / numberOfValues;
adjustedAverage = (totalValue - maxValue) / (numberOfValues - 1);
System.out.println("average is " + average);
System.out.println("adjusted average is " + adjustedAverage);
}}

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;

for (int i = 1; i <= 100; i++)


{
Random MyRand = new Random();
randNum = MyRand.nextInt(6);
randNum += 1;

if (randNum == 1) sum1 = sum1 + 1;


if (randNum == 2) sum2 = sum2 + 1;
if (randNum == 3) sum3 = sum3 + 1;
if (randNum == 4) sum4 = sum4 + 1;
if (randNum == 5) sum5 = sum5 + 1;
if (randNum == 6) sum6 = sum6 + 1;
}
System.out.println("number of value 1 = " + sum1);
System.out.println("number of value 2 = " + sum2);
System.out.println("number of value 3 = " + sum3);
System.out.println("number of value 4 = " + sum4);
System.out.println("number of value 5 = " + sum5);
System.out.println("number of value 6 = " + sum6);

}}

7.2 import java.util.Random;


import java.util.Scanner;
/*
the game with random number program
*/
class RandTest1 {
public static void main(String[] args) {
int randNum = 0;
int inputNum = 0;
System.out.println("Enter a number in the range 1 to 6");
Scanner myObj = new Scanner(System.in);
inputNum = myObj.nextInt();

39
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Random MyRand = new Random();


randNum = MyRand.nextInt(6);
randNum += 1;

if (randNum == inputNum)
System.out.println("Well done");
else
System.out.println("Hard luck");
}}

7.3 import java.util.Random;


import java.util.Scanner;
/*
the game with random number program extended
*/
class RandTest2 {
public static void main(String[] args) {
int randNum = 0;
int inputNum = 0;
int score = 0;
for (int i = 1; i <= 10; i++)
{
System.out.println("Enter a number in the range 1 to 6");
Scanner myObj = new Scanner(System.in);
inputNum = myObj.nextInt();

Random MyRand = new Random();


randNum = MyRand.nextInt(6);
randNum += 1;

if (randNum == inputNum) score = score + 1;


}
System.out.println("Number of correct guesses is " + score);
}}

7.4 This pseudocode design is written as though a function squareroot exists.


This is perfectly valid in a design when the designer knows that such a function
would be provided in a programming language.
areaTin  0.5 * 100 * 100//to convert to an area
//in centimetres squared
areaSquare  areaTin / 10// for each of ten squares
widthSquare  squareroot(areaSquare)
OUTPUT "The width of each square in centimetres is " + widthSquare

7.5 Scanner myObj = new Scanner(System.in);


String inputStr = myObj.nextLine();
char extracted = inputStr.charAt(0)

40
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

7.6 import java.util.Scanner;


/*
to illustrate strings
*/
class NameAndID {
public static void main(String[] args) {
int index = 0;
int index2 = 0;
System.out.println("Enter String");
Scanner inpObj = new Scanner(System.in);
String inputStr = inpObj.nextLine();
String str1 = inputStr.substring(0, 5);
String str2 = inputStr.substring(5);
int length = str2.length();
for (int i = 0; i <= length - 2; i++){
char next = str2.charAt(i);
if (next == ' ') index = i;
}
index2 = index + 1;
String str3 = str2.substring(0, index2);
String str4 = str2.substring(index2);
System.out.println(str1);
System.out.println(str3);
System.out.println(str4);
}}

7.7 import java.io.FileReader;


import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Filereadandwrite {
public static void main(String[] args)throws IOException {
String strInput;
FileReader finputObj = new FileReader("path.txt");
Scanner InObj = new Scanner(finputObj);
strInput = InObj.nextLine();
String OutString = strInput;
FileWriter foutputObj1 = new FileWriter("ProgWriteFile.txt");
for (int i = 0; i < OutString.length(); i++)
foutputObj1.write(OutString.charAt(i));
foutputObj1.close();
finputObj.close();
}}

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();

Random MyRand = new Random();


randNum = MyRand.nextInt(100);
randNum += 1;

if (inputNum1 > randNum) differ1 = inputNum1 - randNum;


else if (inputNum1 < randNum) differ1 = randNum - inputNum1;
else differ1 = 0;
if (inputNum2 > randNum) differ2 = inputNum2 - randNum;
else if (inputNum2 < randNum) differ2 = randNum - inputNum2;
else differ2 = 0;
if (differ1 == differ2) equaldiff = true;
else equaldiff = false;
if (differ1 > differ2) score1 = score1 + 1;
if (differ1 < differ2) score2 = score2 + 1;

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();

System.out.println("Second player enter a number in the


range 1 to 100");

42
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Scanner myObj4 = new Scanner(System.in);


inputNum2 = myObj4.nextInt();
Random MyRand1 = new Random();
randNum = MyRand1.nextInt(100);
randNum += 1;
if (inputNum1 > randNum) differ1 = inputNum1 - randNum;
else if (inputNum1 < randNum) differ1 = randNum - inputNum1;
else differ1 = 0;
if (inputNum2 > randNum) differ2 = inputNum2 - randNum;
else if (inputNum2 < randNum) differ2 = randNum - inputNum2;
else differ2 = 0;
if (differ1 == differ2) equaldiff = true;
else equaldiff = false;
if (differ1 > differ2) score1 = score1 + 1;
if (differ1 < differ2) score2 = score2 + 1;
}
}
if (score1 > score2) System.out.println("Player 1 wins");
if (score1 < score2) System.out.println("Player 2 wins");
if (score1 == score2) System.out.println("A draw");
}}

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

double roofWidth, angle;


double numberDown, numberAlong, numberTiles;
angle = toRadians(30);
roofWidth = 5 / cos(angle);
numberDown = roofWidth / 0.3 + 0.5;
// the 0.5 ensures that the rounding leaves the tiles
//overhanging the wall
numberDown = round(numberDown);
numberAlong = 20 / 0.2 ;
numberTiles = numberDown * numberAlong * 2;
System.out.println("Number of tiles = " + numberTiles);
}}

Skills focus questions


7.1 A
 n empty string has a value "". You can test for a string having zero length. Zero length
means no characters in the string.

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.

A parameter is a variable name identified in the header of a subroutine definition.

 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.

2 a The following are possibilities: substring, replace and toLowerCase.

b The following are examples of Java code:


String newString = oldString.substring(3, 6);
String newString = oldString.replace("ab", "z");
String newString = oldString.toLowerCase();

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.

The toLowerCase method takes no arguments. It changes any upper-case alphabetic


characters to the corresponding lower-case characters. None of any other characters
are changed.

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

public static void main(String[] args) {


int sum = 0;
System.out.println("How many numbers?");
Scanner myObj = new Scanner(System.in);
int howManyInput = myObj.nextInt();
int[] numIn = new int[howManyInput];
for (int i = 0; i <= howManyInput - 1; i++)
{
System.out.println("Number please?");
Scanner myObj1 = new Scanner(System.in);
numIn[i] = myObj1.nextInt();
sum = sum + numIn[i];
}
for (int i = 0; i <= howManyInput - 1; i++)
{
System.out.println(numIn[i]);
}
System.out.println("Sum of above numbers is " + sum);
}}

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;
}

System.out.println("First player please");


System.out.println("Input number in range 1 - 50");
Scanner myObj1 = new Scanner(System.in);
firstNum = myObj1.nextInt();
firstNum = countRandom[firstNum];

System.out.println("Second player please");


System.out.println("Input number in range 1 - 50");
Scanner myObj2 = new Scanner(System.in);
secondNum = myObj2.nextInt();
secondNum = countRandom[secondNum];

if (firstNum > secondNum)


{
System.out.println("First player wins");
System.out.println("Count was " + firstNum);
}
else if (secondNum > firstNum)
{

48
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

System.out.println("Second player wins");


System.out.println("Count was " + secondNum);
}
else
System.out.println("game drawn");
}}

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))

The program code is as follows:


import static java.lang.String.*;
import java.util.Scanner;
/*
search of array with string element
*/
class StringSearch {
public static void main(String[] args) {
String[] threeCharacters = new String[]
{"7cd", "5hy", "2jk", "9re", "3gd", "1dz"};
String arrayString = "";
String outString = "";
System.out.println("Input number in range 1 - 9");
Scanner myObj1 = new Scanner(System.in);
String numIn = myObj1.nextLine();
String digit = numIn.substring(0,1);
String arrayDigit = "";
boolean integerFound = false;
int counter = 0;
while (!integerFound && counter <= 5)
{
arrayDigit = threeCharacters[counter].substring(0,1);
if (digit.equals(arrayDigit))
{
integerFound = true;
outString = threeCharacters[counter].substring(1);
System.out.println(outString);
}
counter = counter + 1;
}
if (integerFound == false)
System.out.println("digit not found");
}}

49
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

8.3 import java.util.Scanner;


import java.util.Random;
/*
bubble sort
*/
class BubbleSort {
public static void main(String[] args) {
int[] arrayforSort = new int[]
{7, 24, 95, 41, 3};
int lastIndex = 4;
int temp = 0;
System.out.println("Original array values");
for (int k = 0; k <= lastIndex; k++)
System.out.println(arrayforSort[k]);
int lastNumber;
lastNumber = lastIndex - 1;
for (int i = 0; i <= (lastIndex - 1); i++)
{
for (int j = 0; j <= lastNumber; j++)
{
if (arrayforSort[j] > arrayforSort[j + 1])
{
temp = arrayforSort[j];
arrayforSort[j] = arrayforSort[j + 1];
arrayforSort[j + 1] = temp;
}
}
lastNumber = lastNumber - 1;
}
System.out.println("Sorted array values");
for (int l = 0; l <= lastIndex; l++)
System.out.println(arrayforSort[l]);
}}

8.4 import java.util.Scanner;


/*
using 2D array
*/
class TwoDarray {
public static void main(String[] args) {
int[][] examMarks = new int[4][2];
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j <= 1; j++)
{
System.out.println("Enter mark for candidate " + (i + 1)
+ " in exam " + (j + 1));
Scanner myObj1 = new Scanner(System.in);
int numIn = myObj1.nextInt();
examMarks[i][j] = numIn;

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]);
}}

Skills focus questions


8.1 T
 here is a separate row for each candidate. If the program has been written so that the identity
of candidate1 is known, then the values in Row 0 can be used correctly. If you were to incorporate
a further column representing the identity of the candidate, the values would have to be integer
values because all cells in a 2D array must have values of the same data type. Doing this would
not be of any benefit.

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

There are three points to note here.

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.

c An array and an iteration.

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

OUTPUT "Enter a pet breed"


INPUT breedChoice
FOR i  0 TO 3
IF petType[i] = petChoice
AND petBreed[i] = breedChoice
THEN list = list +" "
+ petColour[i]
ENDIF
NEXT i
IF list <> ""
THEN
OUTPUT "The options are ", list
ELSE
OUTPUT "None found"
ENDIF
ENDIF

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();

System.out.println("Enter a pet colour");


Scanner myObj3 = new Scanner(System.in);
choice1 = myObj3.nextLine();
for ( int i = 0; i <= 3; i++)
{
if ((petType[i].equals(choice)) && (petColour[i].
equals(choice1)))
list = list + " " + petBreed[i];
}
if (list.isEmpty())
System.out.println("None found");
else System.out.println(list);
}
}
}}

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

OUTPUT "The options are " list


ELSE
OUTPUT "None found"
ENDIF
ENDIF

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"}
};

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)

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

Chapter 9: Designing algorithms


Practice tasks
9.1 Structure design:

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

The flowchart design:

START

Declare and
initialise variables

INPUT bookNumPages

TRUE INPUT bookTitle


bookNumPages > 0
INPUT bookAuthor

FALSE

Store book data

STOP

9.2 1 A representative list would be:

• The date and time for the event.

• The venue to be used.

• The number of people expected to attend.

• The style of the meal (e.g. formal meal with waiting staff or buffet where attendees
help themselves to items).

• Liquid refreshment needed.

• The menu chosen by the customer.

• Contact details for the customer.

58
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

2 In addition to storing all of the above, the following could be stored:


• The number of staff needed.
• Who would be in charge on the day.
• Transport needed for the day of the event.
• Whether the venue has facilities for food preparation.
• Arrangements for delivery of food items to the catering company chefs.
• Number and type of table cloths, cutlery and other items needed on the day.
• Decisions on liquid refreshment to be provided.
• The price agreed with the customer.

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

Calculate Output all


Request Check if data
Store data national data for
data complete
average the month

* 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

9.2 a The following is a reasonable list.

• Date of flight departure.

• Times for departure and arrival.

• Customer details.

• Expected number of passengers.

• Aircraft to be used.

• Names of airports to be used.

• Names of pilots.

• Names of cabin crew.

b The following is a possible structure diagram:

Charter flight

Store booking Store airport Store crew


Flight requested
details details member names

Store pilot or Store cabin


Store names Store names pilots' names crew names
of airports including
intermediate
airport

Store pilot Store pilot &


name co-pilot names

60
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

End-of-chapter questions
1
Weather app

Output the
Input location
forecast

Provide details Identify town Output map Output table


for new town used before

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.

Health centre 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

Chapter 10: Checking inputs


Practice tasks
10.1 import java.util.Scanner;
/*
length check on password
*/
class passwordLength{
public static void main(String[] args) {

boolean PWlengthGood = false;


int lengthPW = 0;

while (PWlengthGood == false)


{

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

10.3 import java.util.Scanner;


/*
checks for presence then checks range
*/
class PresenceCheck {
public static void main(String[] args) {
boolean sensibleValue = false;
int percent = 0;
String stringIn = "";
while (sensibleValue == false)
{
System.out.println("Please enter the percentage");
Scanner theInput = new Scanner(System.in);
stringIn = theInput.nextLine();
Scanner strObj = new Scanner(stringIn);
if (strObj.hasNext() == false)
{
System.out.println("no value entered");
continue;
}
percent = strObj.nextInt();
if (!(percent >= 0 && percent <= 100))
{
System.out.println("not in range, try again");
continue;
}
if (percent >= 0 && percent <= 100)
sensibleValue = true;
}
System.out.println("Percentage is " + percent);
}}

10.4 import java.util.Scanner;


/*
checking integer input
*/
class intCheck {
public static void main(String[] args) {
int intVal = 0;
boolean sensiblePW = false;
while (!sensiblePW)
{
System.out.println("Please enter an integer value");
Scanner intObj = new Scanner(System.in);
if (intObj.hasNextInt())
{
intVal = intObj.nextInt();
break;
}
System.out.println("Not an integer");

63
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

}
System.out.println("Integer entered is " + intVal);
}}

10.5 import java.util.Scanner;


/*
check for illegal number in a string
*/
class numberInString {
public static void main(String[] args) {
String yourName = "";
boolean needName = true;
int len = 0;
boolean problem = false;
while (needName)
{
problem = false;
System.out.println("Please enter your name");
Scanner strObj = new Scanner(System.in);
yourName = strObj.nextLine();
len = yourName.length();
for (int i = 0; i <= (len - 1); i++)
{
if (Character.isDigit(yourName.charAt(i)))
problem = true;
}
if (problem) { System.out.println("no numbers allowed");
}
else {
needName = false;
System.out.println("Name accepted");
}
}
}}

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

String[] months = new String[] {"January", "February", "March",


"April", "May", "June", "July", "August", "September",
"October", "November", "December"};
String monthInput = "";
int[] monthNum = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31};
boolean problemFound = true;
int i = -1;
int numberInMonth = 0;
String leapYear = "";
int dayNumInput = 0;

System.out.println("Name the month");


while (problemFound)
{
Scanner myObj = new Scanner(System.in);
monthInput = myObj.nextLine();
while (problemFound && i <= 10)
{
i = i + 1;
if (monthInput.equals(months[i]))
{
problemFound = false;
numberInMonth = monthNum[i];
}
}
if (problemFound && i == 11)
{
i = -1;
System.out.println("There is a problem");
System.out.println("Enter the month name again");
}
}
if (monthInput.equals(months[1]))
{
System.out.println("Is this a leap year");
System.out.println("If it is enter yes");
Scanner myObj1 = new Scanner(System.in);
leapYear = myObj1.nextLine();
if (leapYear.equals("yes")) numberInMonth = 29;
}

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;
}

4 The pseudocode design:


DECLARE name, password : STRING
DECLARE check : BOOLEAN
DECLARE checkNum : INTEGER
checkNum  1
OUTPUT "Enter name "
INPUT name
OUTPUT "Enter password"
INPUT password
check  nameAndPWCheck(name, password)
IF check
THEN
OUTPUT "Welcome "
ELSE
IF NOT check AND checkNum = 1
THEN
OUTPUT "Error. Please try again "
OUTPUT "Enter name "
INPUT name
OUTPUT "Enter password"
INPUT password
check  nameAndPWCheck(name, password)
IF check
THEN
OUTPUT "Welcome "
ELSE
OUTPUT "Locked Out"
ENDIF
ENDIF
ENDIF

67
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Chapter 11: Testing


Practice tasks
11.1 We can assume that temperature is to be recorded in Celsius.

Normal data examples could be month number 7 and temperature 13.

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.

11.2 There is no defined solution for this activity.

11.3 The corresponding Java program:


import java.util.Scanner;
/*
find minimum value
*/
class MinValue {
public static void main(String[] args) {
int minimumValue = 0;
int nextNumber = 0;
for (int i = 1; i <= 5; i++)
{
System.out.println("Please enter a number");
Scanner theInput = new Scanner(System.in);
nextNumber = theInput.nextInt();
if (nextNumber < minimumValue) minimumValue = nextNumber;
}
System.out.println("Minimum value input is " +
minimumValue);
}}

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

11.4 x y numberOfTimes Output


0
60
15
45 1
30 2
15 3
3

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.

area numberTin Output


30
4
8
8

2 For the second dry-run we input:


• length 3 m
• width 2 m
• coverage for one tin 7 m2
• number of coats 1.

69
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

area numberTin Output


6
0
0
0

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:

area numberTin Output


30
3
6
6

Now let’s consider that the design is changed to the following for the calculation.

area = length * width

area = area *
numberCoats

numberTin = area div coverage

70
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Then the dry-run for input values:


• length 6 m
• width 5 m
• coverage for one tin 8 m2
• number of coats 2
would be recorded as follows.

area numberTin Output


30
60
7
7

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.

2 a Normal, abnormal, extreme, boundary.

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.

Chapter 12: Programming scenario task


End-of-chapter questions
1 import java.util.Random;
import java.util.Scanner;

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");

// the inner loop


for (int i = 1; i <= 10; i++)
{
// following code common to the two players
System.out.println
("Please enter a number in the range 1 to 10");
Scanner myObj = new Scanner(System.in);
int inputNum = myObj.nextInt();

72
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Random MyRand = new Random();


randNum = MyRand.nextInt(10);
randNum += 1;
// following code repeated for each player
if (j == 1)
{
if (inputNum == randNum) score1 = score1 + 1;
total1 = total1 + randNum;
if (randNum > max1) max1 = randNum;
}
else
{
if (inputNum == randNum) score2 = score2 + 1;
total2 = total2 + randNum;
if (randNum > max2) max2 = randNum;
}
}
}
//Choosing the winner has to come outside the iterations
boolean noWinner = true;

if (score1 > score2)


{
System.out.println("Player 1 wins");
noWinner = false;
}
else if (score2 > score1)
{
System.out.println("Player 2 wins");
noWinner = false;
}
if (noWinner)
{
if (max1 > max2)
{
System.out.println("Player 1 wins");
noWinner = false;
}
else if (max2 > max1)
{
System.out.println("Player 2 wins");
noWinner = false;
}
}
if (noWinner)
{
if (total1 > total2)
{
System.out.println("Player 1 wins");
noWinner = false;

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

if (healthIndex[i] >= 200.0)


{
rating[i] = "Red";
totalRed = totalRed + 1;
}
if (healthIndex[i] >= 150.0 && healthIndex[i] < 200.0)
{
rating[i] = "Orange";
totalOrange = totalOrange + 1;
}
else
{
rating[i] = "Green";

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");
}}

4 Only a code fragment is needed for this task.


//Double used instead of float to allow simpler code
//You may have provided a solution using float
//Some extra arrays are needed
double[] averageRange;
averageRange = new double[7];
double[] averageMax;
averageMax = new double[7];

double overallMax = 0.0;


double overallMin = 100.0;

//Nested iteration is needed

//The outer loop starts here


for (int i = 0; i <= 29; i++)
{
double dailyRange = 0.0;
double max = 0.0;

76
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

//The inner loop starts here


for (int j = 0; j <= 6; j++)
{
if (maxTemp[i][j] > overallMax) overallMax = maxTemp[i][j];
if (minTemp[i][j] < overallMin) overallMin = minTemp[i][j];

dailyRange = dailyRange + (maxTemp[i][j] - minTemp[i][j]);


max = max + maxTemp[i][j];
}
averageRange[i] = dailyRange / 7;
averageMax[i] = max / 7;
}
//After the nested loops have completed some output can be created
// in a new loop
for (int k = 0; k <= 29; k++)
{
System.out.println("For " + school[k] + " school");
System.out.println
("the average range and maximum values are");
System.out.println(averageRange[k] + " " + averageMax[k]);
}
//These two outputs must come outside the loops
System.out.println("The highest temperature was " + overallMax);
System.out.println("The lowest temperature was " + overallMin);

5 Only a code fragment is needed for this task.


/*
You have been asked to assume that two arrays have already been
declared and that input statements have been written for the data
stored in these arrays
In the 2D array named distance a value of -1 has been entered in a
cell if the member did not attempt one of the runs
*/
//Some extra arrays are needed
//You might have chosen to use the one line statement versions
int[] numberRuns;
numberRuns = new int[numberMembers];
//Using double instead of float simplifies the code
//You might have chosen to use float
double[] averageDistance;
averageDistance = new double[numberMembers];
double[] bestDistance;
bestDistance = new double[numberMembers];
String[] category;
category = new String[numberMembers];

//Using a loop to initialise values in the arrays


for (int ij = 0; ij < numberMembers; ij++)
{
numberRuns[ij] = 0;

77
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

averageDistance[ij] = 0.0;
bestDistance[ij] = -20.0;
category[ij] = "";
}
double distanceCovered;

//Outer loop starts for a nested iteration


for (int i = 0; i < numberMembers; i++)
{
distanceCovered = 0.0;
//Inner loop starts for up to three runs completed
for (int j = 0; j <= 2; j++)
{
if (distance[i][j] > -1.0)
{
numberRuns[i] = numberRuns[i] + 1;
distanceCovered = distanceCovered + distance[i][j];
if (j == 2) averageDistance[i] =
distanceCovered / numberRuns[i];
if (distance[i][j] > bestDistance[i]) bestDistance[i] =
distance[i][j];
}
category[i] = "Club";
if (bestDistance[i] >= 5.0 && bestDistance[i] < 7.0)
category[i] = "Championship";
if (bestDistance[i] >= 7.0) category[i] = "Elite";
}
//Some output outside the inner loop but still inside the outer
// loop of values for one member
System.out.println("For " + members[i] + " values are:");
System.out.println("Runs completed = " + numberRuns[i]);
System.out.println
("Average distance = " + averageDistance[i]);
System.out.println("Best distance = " + bestDistance[i]);
System.out.println("Category = " + category[i]);
}

Chapter 13: Examination practice


1 Maximum of six marks, one mark for each of the following:
• Declare and initialise variables.
• Decision to identify vote.
• Correct incrementing of vote records.
• Correct loop that iterates for 601 inputs.
• Correct calculation of percentage.
• Output of name and percentage.

78
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

Example of flowchart – any correct solution will achieve marks.

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

Example of pseudocode – any correct solution will achieve marks.


DECLARE vote : STRING
DECLARE Faraday : INTEGER
DECLARE Curie : INTEGER
DECLARE counter : INTEGER
DECLARE percent : REAL
vote  ""
Faraday  0
Curie  0
percent  0.0
FOR counter  1 to 601
OUTPUT "Enter Vote"
INPUT vote
IF Vote = "Faraday"
THEN
Faraday  Faraday + 1
ELSE
Curie  Curie + 1
ENDIF
NEXT counter
IF Faraday > Curie
THEN
percent  100.0 * Faraday / 601
OUTPUT "Winner is Faraday with " , percent
ELSE
percent  100.0 * Curie / 601
OUTPUT "Winner is Curie with " , percent
ENDIF

2 Maximum of eight marks.

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.

• Comparison for High is incorrect / IF Marks <= High.


• The symbol should be > (accept >=) / IF Marks > High.

• Low is not assigned a value / Marks  Low is wrong way round.


• Low must be assigned the value of Marks / Low  Marks.

• Average is wrongly calculated / Count ÷ Total is wrong way round.


• Average  Total / Count.

3 a Maximum of four marks from:


• The check digit is generated by a calculation completed on the other numbers.
• An algorithm is applied to the numbers (accept by example) to arrive at a total.

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)}.

Pseudocode Type of validation


INPUT ISBN
IF ISBN = ""
THEN [1] Presence Check
OUTPUT "Error"
ENDIF
INPUT ISBN
IF LENGTH(ISBN) < 13
THEN [1] Length Check
OUTPUT "Error"
ENDIF

c Maximum of three marks from one for each correct data value:

Type of data Example


Normal Any integer value between 12 and 198 (reject 11 or 199, they are extreme)
Abnormal Any value not of an integer data type, or integer values > 200 or <11
Extreme 11 or 199 only

4 Maximum of five marks from one for each correct column:

Number Count Total Large Output


0 0 0 0
15 1 15
0 2
14 3 29
0 4
12 5 41
19 6 60 3
11 7 71
−6 8
7 21

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

5 a Maximum of five marks with one each from:


• The required username is input.
• A loop to check the whole array (array can be indexed from 0 or 1, e.g. 0 to 599 or
1 to 600).
• A loop counter is correctly used to identify index locations in the array.
• Selection is used to check required username at each index location.
• If the match is true output the correct index location.
• End the search when a match is found.
• If there is no match at the end of the loop output correct message.

Example flowchart:

START

username ← ""
counter = 0

INPUT
username

username = TRUE
OUTPUT
netName(counter) counter

FALSE

STOP
counter ←
counter + 1

FALSE counter = TRUE


OUTPUT
599
"No record"

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

b Maximum of three marks from:


• For each increment of the counter.
• If the string stored in the array element for that index value is not equal to the string
search value,
• then check if it is alphabetically higher than the string search value.
• If it is, exit the loop,
• because the search value cannot be stored in any of the remaining array elements.

6 Maximum of three marks from:


• The use of nested loops.
• The correct range of loop counters.
• Loop counters used accurately to determine index locations.

Example pseudocode:
FOR Counter1 = 0 TO 8
FOR Counter2 = 0 TO 8
Board (Counter1, Counter2)  "Free"
NEXT Counter2
NEXT Counter1

7 Maximum of six marks from:


• Inputs the product number for checking.
• Correctly checks length and rejects if it fails the test.
• Correctly uses a substring to identify the first 4 characters.

83
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

• Correctly checks the first four characters and rejects if it fails.


• Accepts all other product numbers.
Example flowchart:

START

prodNum ←""
INT Length ← 0

INPUT
prodNum

TRUE
length
<> 10

FALSE

FALSE SUBSTRING TRUE


OUTPUT (prodNum, 1, 4) OUTPUT
"Accepted" <> "PROD" "Rejected"

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

8 Maximum of four marks from:


• Correct use of the terms CASE, OTHERWISE and END CASE.
• Correctly links CASE to input Score.
• Has CASE conditions for >100, >80 and >60.
• Has used OTHERWISE to replace the ELSE statement.
Example pseudocode:
DECLARE Score : INTEGER
Score  )
INPUT Score
CASE OF Score
> 100 : OUTPUT "Excelling"
> 80 : OUTPUT "Good"
> 60 OUTPUT "Acceptable"
OTHERWISE OUTPUT "Below expectations"
ENDCASE

9 Maximum of three marks from:


• The function takes Celsius (or equivalent) as a parameter value.
• The value is retuned using RETURN or a function name.
• Type is defined for the function.

Example pseudocode:
FUNCTION convert(tempCelsius: REAL) RETURNS REAL
DECLARE tempFahrenheit : REAL
tempFahrenheit  tempCelsius * 1.8) + 32
RETURN tempFahrenheit
ENDFUNCTION

10 a Maximum of two marks from:


• Variables can change during execution of the program.
• Constants cannot be changed / are fixed during execution of the program.

b Maximum of six marks from one for each correct data type:

Variable Most appropriate data type


students integer
idnumber string
weight real (Accept float / decimal)
passed Boolean
name string
grade character (reject string)

85
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

11 Maximum of eight marks.


This would be marked with 1 mark per correct box (plus the correct True/False indicators).
However, this is not the only possible solution. If the captions for the options are given as
complete ranges, such as age > 9 AND age > 18, there is no necessity for them all to be in order.

INPUT age

TRUE
classification
age < 10
← "child"

FALSE

TRUE
classification
age < 18
← "junior"

FALSE

TRUE
classification
age < 60
← "adult"

FALSE

classification
← "senior"

STOP

12 a Maximum of two marks.

A name (one mark) used in a program to identify a memory location (one mark).

86
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

b One mark for each correct value for a data type.

Data element Most appropriate data type


Student name string
Student identifier string
Mark integer
Percentage real / float
Comments string
Re-test needed Boolean

13 a i One mark for each correct answer to maximum of three marks.

Once written, the subroutine can be used many times without the need for the
code to be written again.

Subroutines may be made available by the programming language.

Subroutines already available are likely to be more reliable.

The program code would be shorter.

Programs would be more understandable.

Programs would take less time to write.

Program complexity would be reduced.

Subroutines could be separately coded by different programmers.

Subroutines could be individually tested.

ii One mark for each correct answer to maximum of two marks.

A function returns a value; a procedure does not.

A function has a defined type; a procedure does not.

A function is used as part of an expression on the right-hand side of an assignment


statement; a procedure is called by a statement consisting of its name, possibly preceded
by CALL.

One mark each for i, ii and iii.


b 

i milesToKm

ii CALL milesToKm(milesDistance)

(accept an answer with a second argument KmDistance)

iii KmDistance milesToKm(milesDistance)

87
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

14 Maximum of four marks, one mark each for a, b, c and d.

Pseudocode solutions (note that the first index is numbered 1 in pseudocode):

a newString  UCASE(oldString)

b newString  SUBSTRING(oldString, 8, 1)

c newString  SUBSTRING(oldString, 1, 1)

d newString  SUBSTRING(oldString, 5, 4)

Java solutions (note that the first index is zero):

a newString = oldString.toUpperCase();

b newString = oldString.Substring(7);

c newString = oldString.Substring(0,1);

d newString = oldString.Substring(4);

15 Maximum of five marks.

Membership
application decision

Receive
Receive details Send decision
supporting Store decision
of applicant to applicant
details

Sorry
Welcome to application
membership rejected

System name: one mark.

Second row: one mark for each pair of labels.

Third row: one mark for the two labels.

One mark for the option symbol.

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.

a It is a sorting algorithm/bubble sort.

b There is a one-dimensional/1D array used.

There are two For loops.

There are nested iterations.

There is a procedure called swap being used.

The coding for swap will have been written elsewhere.

The loops allow successive access to elements of the array.

There are two IF statements.

There are several assignment statements.


17 a Maximum of six marks from these edits made to the pseudocode (one mark for each):
• Changed Name1 and Name2 to something more descriptive.
• Provided a comment for the function.
• Gave the function a more descriptive name.
• Replaced i,j,k,l,m with something a little more related to a set of times.
• Replaced t with an identifier that indicates it is a total in minutes.
• Split RETURN ROUND(t / 5) into two lines and used a descriptive identifier.
• Provided a comment to explain what CASE was doing.
• Replaced a,b,c,d,e with identifiers more related to times.
• Replaced Ave with Average or Mean.
• Added a minimum of three empty lines to break up the algorithm and make it easier
to read.

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

//Times to be entered in minutes as integers


FOR Counter  1 TO 5

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"

b Maximum of six marks (one mark for each of the following):


• Program that generally works without a CASE or FUNCTION present
(accept up to two typos).
• Program that works with no typos.
• Program that is manageable.
• Program that is less than 10 lines long (excluding empty lines).
• A successful use of a loop to obtain INPUT of times (does not need to be a FOR loop).
• Still produces the same output.

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"

18 Maximum of six marks.

a One mark for both answers: MinLives, MaxLives

b One mark for both answers: Lives, GameOver

c One mark for: Global variables can be accessed anywhere in a program.

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.

19 Maximum of six marks, one mark per bullet point:


• Opening the correct file.
• Reading in the value.
• Adding 1 to the value.
• Storing new value in the correct file.
• Calling gameOver().
• Closing the file.
• Closing file before calling gameOver().
Pseudocode example answer:
DECLARE value : STRING
OPENFILE Score.txt FOR READ
READFILE Score.txt, value
CLOSEFILE Score.txt
value  value + 1
IF value > 9
THEN
CALL gameOver()
ENDIF
OPENFILE Score.txt FOR WRITE
WRITEFILE Score.txt, value
CLOSEFILE Score.txt
Java example answer:
[Note that the incremented integer value cannot be output directly. It first has to be converted
to a String value.]
/*
The following header code would not be expected in an answer to the
question asked. It is included for you to compare if your answer
includes header code.
*/
import java.io.*;
import java.io.IOException;
import java.util.Scanner;
public class IntToFile {

91
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK

/* The code for the definition of the procedure gameOver would be


needed here to have a fully working program.
*/
public static void main(String[] args) throws IOException {
// The following code is all that the answer would need for full
marks.
int value;
FileReader finputObj = new FileReader("Score.txt");
Scanner InObj = new Scanner(finputObj);
value = InObj.nextInt();
finputObj.close();
value = value + 1;
String val = String.valueOf(value);
FileWriter foutputObj = new FileWriter("Score.txt");
foutputObj.write(val);
foutputObj.close();
if (value > 9) gameOver();
}}

20 Maximum of six marks, one mark per bullet point:


• Inputs firstname and lastname.
• Converts firstname and lastname to lowercase string.
• Correctly selects first two letters of firstname.
• Correctly selects last five letters of lastname.
• Correctly uses a function to generate random numbers to create a six-figure password
that does not start with 0. (Note: it does not need to collect all values but MUST
generate most available values.)
• Outputs username and password.

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

System.out.println("Username is " + userName);


String[] digit = new String[5];
Random MyRand = new Random();
int int1 = MyRand.nextInt(10);
if (int1 != 9) int1 += 1;
String char1 = String.valueOf(int1);
for (int i = 0; i <= 4; i++)
{
int1 = MyRand.nextInt(10);
digit[i] = String.valueOf(int1);
}
String password = char1 + digit[0] + digit[1] + digit[2] +
digit[3] + digit[4];
System.out.println("Password is " + password);
}}

21 Maximum of seven marks.

a Three marks from the following, one mark per bullet:


• The indexes in the 2D array provide a coordinate system to represent the map.
• Only one name is needed for a 2D array instead of a set of different names for
the 1D arrays.
• Relationships between locations in different rows are easier to program in
a single array than in many arrays.
• A loop can search through all locations in a row, a column, a diagonal or the
whole array.
• A nested loop set can be used to quickly read from or write to all locations
in the array.

b One mark for: DECLARE Map : ARRAY [0:9 , 0:9] OF STRING

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

You might also like