CH 8
CH 8
Chapter 8
Programming
IN THIS CHAPTER YOU WILL:
• write programs with the library routines MOD, DIV, ROUND and 1 Why do you think all these languages have similar constructs?
RANDOM 2 Find some constructs that are in one language, e.g. VB.NET, and not
• understand what makes a program maintainable in another, e.g. Python.
GETTING STARTED
You might need to turn one data type into another data type. This is not name = "Alex"
required as part of the specification, but when you are programming in your print("Hello", name)
chosen language you might have to do it for your program to work. This is Java
called casting. You can do this by using the name of the data type you want
the data to become. public static void main(String args[]){
String name = "Alex";
Example 1
System.out.println("Hello " + name);
Convert a string to an integer: }
Number ← int("123") Example 2
VB.NET Output the cost of an item stored in the variable cost:
Dim number As Integer OUTPUT("The cost is " , Cost)
number = Convert.ToInt16("123")
VB.NET
Python
Dim cost As Single = 22.54
number = int("123") Console.WriteLine("The cost is " & cost)
Java
Python
public static void main(String args[]){
Integer number = Integer.parseInt("123"); cost = 22.54
} print("The cost is", cost)
Java
Example 2
Convert a number to a string:
public static void main(String args[]){
Double cost = 22.54;
Value ← string(22.4) System.out.println("The cost is " + cost);
VB.NET }
Dim value As String Example 3
value = Convert.ToString(22.4) Output the number of balloons stored in the variable balloon:
Python OUTPUT("There are " , Balloon , " balloons")
value = str(22.4) VB.NET
Java Dim balloon As Integer = 100
public static void main(String args[]){ Console.WriteLine("There are " & balloon &
String value = Double.toString(22.4); "balloons")
} Python
Questions balloon = 100
print("There are", balloon, "balloons")
1 Tick one or more boxes in each row to identify whether each statement
refers to variables and/or constants. Java
public static void main(String args[]){
Statement Variable Constant
Integer balloon = 100;
You cannot change the value when System.out.println("There are " + balloon +
the program is running. " balloons");
It has an identifier. }
It is a memory location.
You can change its value when the
program is running.
It stores a piece of data.
A program might need the user to enter (input) some data. To do this, the
+ Adds two values together. 10 + 2 gives 12
command word INPUT is used. This cannot appear on its own, otherwise the 11.3 + 9 gives 20.3
data entered will disappear into space. So you need to do something with it, for - Subtracts the second value from the 10 - 2 gives 8
example, store it in a variable. first. 11.3 - 9 gives 2.3
Example 1 * Multiplies two values together. 10 * 2 gives 20
Input a number and store it in a variable: 11.3 * 9 gives 101.7
INPUT Number / Divides the first number by the 10 / 2 gives 5
VB.NET
second. 11.3 / 9 gives 1.256
Dim number As Integer DIV Gives the whole number after the DIV(10, 2) gives 5
number = Console.ReadLine
first number is divided by the DIV(11, 9) gives 1
second, i.e. it ignores any decimals.
Python MOD Gives the remainder after the first MOD(10, 2) gives 0
number = int(input()) number is divided by the second, i.e. MOD(11, 9) gives 2
how many are left.
Java
^ Power of. 2 ^ 3 = 8
public static void main(String args[]){ 3 ^ 2 = 9
Scanner scanner = new Scanner(System.in);
Integer number = Table 8.2: Common operators
Integer.parseInt(scanner.nextLine());
} MOD has one special use in programming. It can be used to work out if a
number is odd or even. If you perform MOD 2 to a number and it returns 0 then
it is even, if it returns 1 then it is odd.
Example 2
Example: MOD(10, 2) = 0 therefore 10 is even.
Tell the user to enter a word and store it in a variable:
MOD(11, 2) = 1 therefore 11 is odd.
OUTPUT("Enter a word")
INPUT Word SKILLS FOCUS 8.1
VB.NET
MOD VS DIV
Dim word As String
It is important that you know the difference between MOD and DIV. They are
Console.WriteLine("Enter a word")
similar in their function, but are often confused with division (/). You need to
word = Console.ReadLine be able to use both of these, both to identify the result of the operation, and
Python to be able to write programs using them. In this Skills Focus you will be
calculating the result from a MOD and DIV operation.
number = input("Enter a word")
DIV gives the whole number after the division and ignores any remainder.
Java
a 10 / 2 =v5 There is no remainder, so DIV(10, 2) = 5.
public static void main(String args[]){
System.out;println("Enter a word") b 20 / 7 = 2.857 There is a remainder, so DIV(20, 7) = 2 (ignore the
numbers after the decimal point).
Scanner scanner = new Scanner(System.in);
String word = scanner.nextLine(); c 100 / 21 = 4.762 There is a remainder, so DIV(100, 21) = 4 (ignore the
} numbers after the decimal point).
MOD gives the remainder after division. This is not the decimal point, but
PROGRAMMING TASK 8.1 how many values are left.
a 10 / 2 = 5 There is no remainder, so MOD(10, 2) = 0.
A program asks the user to register for a new account. The user needs to
enter key information, e.g. name, date of birth, select a username, etc. b 20 / 7 = 2.857 There is a remainder. Take the DIV result (2) and
multiply it by the divisor number. 7 * 2 = 14. The remainder is how
Getting started
many more numbers are between 14 and the 20 (20 − 6). The answer
1 Work in pairs to list the different items that the program will collect. is 6.
2 Identify the most appropriate data type for each of the items you have c 100 / 21 = 4.762 There is a remainder. Take the DIV result (4) and
identified. multiply it by the divisor 21 * 4 = 84. The remainder is 100 − 84 which
is 16.
Practice d 30 / 9 = 3.3333 There is a remainder. 9 * 3 = 27. 30 − 27 = 3.
1 Select appropriate variables for the items you have identified that you Questions
are going to store.
1 Calculate the result for each of these equations:
2 Write a program to ask the user to enter each of the items in turn.
Read in each value and store it in an appropriate variable. a DIV(9, 2)
3 Output a message confirming the details that the user has entered. b DIV(17, 3)
2 Calculate the result for each of these equations:
Challenge a MOD(9, 2)
1 The username needs to be at least 8 characters long. Find out how to b MOD(17, 3)
work out the length of a string input and output how many characters
the user has entered.
2 Find out how to use selection statements to check the length of the
string and if it is not long enough, ask the user to enter a different
username.
COMPUTER SCIENCE IN CONTEXT
public static void main(String args[]){ <= Less than or 10 <= 11? would give TRUE. 10 is less
Scanner scanner = new Scanner(System.in); equal to than or equal to 10.
System.out.println("Enter a colour"); 10 <= 10? would give TRUE. 10 is less
String colour = scanner.nextLine(); than or equal to 10.
System.out.println("Enter your name");
String name = scanner.nextLine(); 11 <= 10? would give FALSE. 11 is not
less than or equal to 10.
System.out.println(name + " your favourite
colour is " + colour); > Greater than 10 > 11? would give FALSE. 10 is not
} greater than 11.
This is a sequence. It has 3 lines are executed once, and in the order they are 10 > 10? would give FALSE. 10 is not
written greater than 10.
(line 1, then 2 then 3).
11 > 10? would give TRUE. 11 is greater
Example 2 than 10.
X ← 1
Y ← 2 >= Greater than 10 >= 11? would give FALSE. 10 is not
Z ← 3 or equal to greater than or equal to 11.
Total ← X + Y + Z 10 >= 10? would give TRUE. 10 is greater
OUTPUT("Enter the first value") than or equal to 10.
INPUT Value1 11 >= 10? would give TRUE. 11 is greater
VB.NET than or equal to 10.
Dim X As Integer = 1
Table 8.3: Logical operators
Dim Y As Integer = 2
Dim Z As Integer = 3
Dim total As Integer = X + Y + Z
Dim value1 As String SKILLS FOCUS 8.2
Console.WriteLine("Enter the first value")
COMPARISON OPERATORS
value1 = Console.ReadLine
Comparison operators are used in comparison statements; both selection
Python and iteration. The operators are very similar and you need to know the
x = 1 difference to make sure you know, a, how to read the statements to make
y = 2 sure you follow an algorithm correctly, and b, which to select when you are
z = 3 writing your own comparison statements.
total = x + y + z A common error is when less than and greater than are confused. The
value1 = int(input("Enter the first value")) shape of them can help you to work out which is correct.
IF(10 < 2) The smaller part of the < is nearest the left, the 10. This is
Java the less than part. So the statement reads if 10 is less than 2. This would
result in False because 10 is not less than 2.
public static void main(String args[]){
Integer X = 1; IF(150 > 25) The larger part of the > is nearest the left, the 150. This
Integer Y = 2; is the greater than part. So the statement reads if 150 is greater than 25.
Integer Z = 3; This would result in True because 150 is greater than 25.
Integer total = X + Y + Z; IF(33 <= 34) The smaller part of the <= is nearest the left, the 33. This
String value1; is the less than part. There is also an equals after the less than sign. So the
System.out.println("Enter the first value"); statement reads if 33 is less than or equal to 34. This would result in True,
Scanner scanner = new Scanner(System.in); 33 is less than 34.
value1 = scanner.nextLine(); IF(50 >= 70) The larger part of the >= is nearest the left, the 50. This
} is the greater than part. There is also an equals after the less than sign. So
the statement reads if 50 is greater than or equal to 70. This would result in
Questions False, 50 is not greater than or equal to 70.
4 Give the result from the following calculations: Questions
a 10 + 20 1 Put each statement into words:
b 20 a IF(1 < 2)
c 100
10 Look at the left of the symbol. Is it small or large? Write the first
number, followed by the symbol name, then the second number.
d 50 - 15
e 20 DIV 2 b IF(6 > 3)
f 39 DIV 6 c IF(999 >= 998)
g 20 MOD 2 d IF(34 <= 77)
h 40 MOD 6 2 Work out if each statement is True or False.
5 Write a program to take a number as input, multiply it by 2 and output the a IF(66 < 40)
result.
b IF(100 > 101)
6 Write a program to store the numbers 10 and 12 in constants, add them
together and then output the result. c IF(90 <= 45)
7 Write a program to ask a user to enter their age and name, then output a d IF(30 >= 30)
message that uses both values, e.g. Hello Suzie you are 15 year old.
IF statements Example 1
The command IF is followed by a condition that is created using the logical In this example if the two values are the same it outputs "That's
operators. There are three stages of IF statements; IF, ELSE and ELSEIF. correct". If they are not the same then the ELSE runs, it will output
"Incorrect".
IF has one comparison and the code inside the IF will only run if that
condition is True. If it is not true, the code in the IF statement will not run. Num ← 10
OUTPUT("Enter a number")
It follows the structure:
INPUT Guess
IF comparison THEN IF Num = Guess THEN
Statements that run if the comparison is OUTPUT("That's correct")
true ELSE
ENDIF OUTPUT("Incorrect")
Example 1 ENDIF
This program will check the value in the variable num1 is equal to 10. If it is, it VB.NET
will output the word True. Dim num As Integer = 10
Num1 ← 10 Dim guess As Integer
IF Num1 = 10 THEN Console.WriteLine("Enter a number")
OUTPUT("True") guess = Console.ReadLine
ENDIF If num = guess Then
Console.WriteLine("That's correct")
Else
VB.NET Console.WriteLine("Incorrect")
End If
Dim num1 As Integer = 10
If num1 = 10 Then Python
Console.WriteLine("True") num = 10
End If guess = int(input("Enter a number"))
Python if num == guess:
print("That's correct")
num1 = 10
else:
if num1 == 10:
print("Incorrect")
print("True")
Java
Java
public static void main(String args[]){
public static void main(String args[]){
Integer num = 10;
Integer num1 = 10;
Integer guess;
if(num1 == 10){
Scanner scanner = new Scanner(System.in);
System.out.println("True");
System.out.println("Enter a number");
}
guess =
}
Integer.parseInt(scanner.nextLine());
Example 2 if(num == guess){
This program will check if the value input is greater than the one stored in the System.out.println("That's correct");
variable. }else{
OUTPUT("Enter a number") System.out.println("Incorrect");
INPUT ValueInput }
StoredValue ← 100 }
IF ValueInput > StoredValue THEN Example 2
OUTPUT("It is more than 100") In this example, it will output the smallest number, or one of the numbers if
ENDIF they are
VB.NET both the same.
Practice
1 Discuss in pairs which type of selection statement would be most
appropriate for checking the symbol input.
2 Edit your program to use your chosen selection statement to check
the symbol the user has entered. Depending on the symbol, perform
the required calculation and output the result.
Challenge
1 Discuss in pairs how the inputs could be repeatedly asked for until a
valid entry is given. For example, keep entering a symbol until one of
the valid ones is entered.
2 Implement your idea for repeatedly asking for the symbol to be input
until a valid one is entered.
3 Include additional mathematical operations, for example, power of,
modulus division.
Example 3 Python
Add together the first 100 numbers: inputValue = "Yes"
Total ← 0 while inputValue == "Yes":
FOR Number ← 1 TO 100 inputValue = input("Do you want to
Total ← Total + Number continue?")
NEXT Number Java
VB.NET public static void main(String args[]){
Dim total As Integer = 0 String inputValue = "Yes";
For number = 1 To 100 Scanner scanner = new Scanner(System.in);
total = total + number while(inputValue.equals("Yes")){
Next System.out.println("Do you want to
continue?");
Python inputValue = scanner.nextLine();
total = 0 }
for number in range(1, 101): }
total = total + number
Java Example 2
public static void main(String args[]){ Outputting the numbers 1 to 10:
Integer total = 0; Number ← 1
for(Integer number = 1; number <= 10; WHILE Number < 11 DO
number++){ OUTPUT(Number)
total = total + number; Number ← Number + 1
} ENDWHILE
}
VB.NET
You can change the amount that you increase the variable by each time you
loop. This is by using STEP. STEP 1 will increase the counter by 1 each
Dim number As Integer = 1
time. STEP -1 will decrease the counter by 1 each time. STEP 0.5 will
While number < 11
increase the counter by 0.5 each time. Console.WriteLine(number)
number = number + 1
Example 1 End While
Output the numbers 10 to 1: Python
FOR Number ← 10 TO 1 STEP -1 number = 1
OUTPUT(Number) while number < 11:
NEXT Number print(str(number))
VB.NET number = number + 1
For number = 10 To 1 Step -1 Java
Console.WriteLine(number) public static void main(String args[]){
Next Integer number = 1;
Python while(number < 11){
for number in range (10, 0, -1): System.out.println(number);
print(str(number)) number++;
}
Java }
public static void main(String args[]){ Example 3
for(Integer number = 10; number >= 1;
number--){ Asking the user to enter a number until they guess the stored number
correctly:
System.out.println(number);
} Number ← 5
} Guessed ← FALSE
Example 2 WHILE Guessed = FALSE DO
OUTPUT("Guess the number")
Output the numbers from 11 to 20, increasing by 0.5 each time. (No example is INPUT Guess
given for Python as it does not support stepping in decimals.)
IF Guess = Number THEN
FOR Value ← 11 TO 20 STEP 0.5 Guessed ← TRUE
OUTPUT(Value) ENDIF
NEXT Value ENDWHILE
VB.NET
VB.NET
Dim number As Integer = 5
For value = 11 To 20 Step 0.5
Dim guessed As Boolean = False
Console.WriteLine(value)
While guessed = False
Next
Console.WriteLine("Guess the number")
Java number = Console.ReadLine
public static void main(String args[]){ If guessed = number Then
for(Double value = 11.0; value <= 20.0; guessed = True
value += 0.5){ End If
System.out.println(value); End While
} Python
}
number = 5
Pre-condition guessed = False
while guessed == False:
A pre-condition loop tests the condition before starting the loop. This means
that if the condition is false, the code inside the loop will not run. It loops while
guess = int(input("Guess the number"))
the condition is true. It stops looping when the condition is false. if guess == number:
guessed = True
A WHILE loop is a pre-condition loop. It has the structure:
Java
WHILE condition DO
Code that will run when the condition is public static void main(String args[]){
true Scanner scanner = new Scanner(System.in);
ENDWHILE Integer number = 5;
Boolean guessed = false;
Example 1 while(guessed == false){
Looping while the user enters “Yes”.
System.out.println("Guess the number");
Integer guess =
InputValue ← "Yes" Integer.parseInt(scanner.nextLine());
WHILE InputValue = "Yes" DO if(guess == number){
InputValue ← INPUT("Do you want to guessed = true;
continue?") }
ENDWHILE }
VB.NET
}
Dim inputValue As String = "Yes"
While inputValue = "Yes"
Console.WriteLine("Do you want to
continue?")
inputValue = Console.ReadLine
End While
Post-condition loop PROGRAMMING TASK 8.3
A post-condition loop runs the code inside the loop once, and then checks the
condition at the end of the loop. This means that the code will always run once. A program needs to ask the user to guess what number the game is
‘thinking of’. The game should store the number for the user to guess. The
A REPEAT UNTIL loop is a post-condition loop. It has the structure: user should continually guess until they get the correct answer.
REPEAT Getting started
Code that runs inside the loop
1 Work in pairs to identify the inputs, processes and outputs required
UNTIL Condition for this system.
In this case it continues until the Condition becomes True. It loops while the 2 Discuss which construct(s) will be needed: sequence, selection
condition is False. and/or iteration.
Looping until the user enters Yes. (No example is given for Python as it does
Practice
not have an in-built post-condition loop.)
1 Write a program for the algorithm you have designed.
REPEAT
OUTPUT("Do you want to stop?") 2 Change the program so that the program outputs “lower” if their
INPUT Answer guess is too high, and “higher” if their guess is too low.
UNTIL Answer = "Yes"
VB.NET Challenge
Dim answer As String 1 Change the program to count how many times the user guesses the
Do number before they get it correct. Output the total when they guess
correctly.
Console.WriteLine("Do you want to stop?")
answer = Console.ReadLine 2 Change the program to allow a user to enter the number for the
Loop Until answer = "Yes" player to guess at the start of the program.
Java
Java has a do while loop, so it loops while the condition is true, not until it is SKILLS FOCUS 8.3
true.
public static void main(String args[]){ CONVERTING A FOR LOOP TO A WHILE LOOP
Scanner scanner = new Scanner(System.in); The three different types of loop (count-controlled, pre-condition and post-
String answer = "Yes"; condition) can often be written as a different type of loop. For example, a
do{ count-controlled loop can be written using a pre-condition loop, or a post-
condition loop. Pre-condition and post-condition loops can be rewritten as
System.out.println("Do you want to
each other. Some pre- and post-condition loops can be written as a count-
stop?"); controlled - but only if their comparisons are for a count, e.g. looping 10
answer = scanner.nextLine(); times.
}while(!answer.equals("Yes"));
A computational thinking skill is the ability to take a loop and convert it to
} other loops. This demonstrates your understanding of how the different
Example 2 loops work and the characteristics of each type of loop. Therefore it is good
practice to experiment by converting one loop into a different type.
Outputting the numbers 1 to 10. (No example is given for Python as it does not
have an in-built post-condition loop.) For example, converting a for loop to a while loop.
Number ← 1 Consider the for loop:
REPEAT FOR X ← 1 TO 10
OUTPUT(Number) OUTPUT(X)
Number ← Number + 1 NEXT
UNTIL Number > 10 Step 1: Declare the variable used as the counter. In this example the
variable is x, the value is 1.
VB.NET Step 2: Take the last value and put it in the while loop condition. In this
Dim number As Integer = 1 example loop until it is 10, so the condition is while x < 11.
Do Step 3: Increment the counter in the loop. The counter is x so x needs to
Console.WriteLine(number) have 1 added to it.
number = number + 1 X = 1 (Step 1)
Loop Until number > 10 WHILE X < 11 DO (Step 2)
Java OUTPUT(X)
public static void main(String args[]){ X ← X + 1 (Step 3)
Integer number = 1; ENDWHILE
do{ Questions
System.out.println(number); 1 Convert the following FOR loop to a WHILE loop.
number++; FOR Count ← 0 TO 100
}while(number <= 10); OUTPUT(Count + Count)
} NEXT
Example 3 Step 1: Declare your variable with its starting value.
Asking the user to enter a number until they guess the correct number. (No Step 2: Take the last value and put it in the while condition.
example is given for Python as it does not have an in-built post-condition loop.)
Step 3: Increment the counter in the loop.
NumberToGuess ← 15 2 Convert the following FOR loop to a WHILE loop.
REPEAT FOR New ← 100 TO 111
OUTPUT("Guess the number") OUTPUT(New ^ New)
INPUT Guess NEXT
UNTIL Guess = NumberToGuess
VB.NET Questions
Dim numberToGuess As Integer = 15 13 Describe the difference between a pre-condition and post-condition loop.
Dim guess As Integer
Do 14 A program needs a loop that will run 50 times. Which type of loop would
be most appropriate?
Console.WriteLine("Guess the number")
guess = Console.ReadLine 15 Write a program to output the numbers 100 to 200.
Loop Until guess = numberToGuess 16 Write a program to output the 5 times table (from 5 times 1, to 5 times
Java 12).
17 Write a program to ask the user to enter a number continually, until they
public static void main(String args[]){
enter the number 10, using a post-condition loop.
Scanner scanner = new Scanner(System.in);
Integer numberToGuess = 15; 18 Write a program to output the word “Hello” until the user enters the word
Integer guess; “stop”, using a pre-condition loop.
do{ 19 Convert the following count-controlled loop to a pre-condition loop.
System.out.println("Guess the number"); FOR Counter ← 1 to 10
guess = OUTPUT(Counter * Counter)
Integer.parseInt(scanner.nextLine()); NEXT Counter
}while(numberToGuess != guess);
}
VB.NET
8.8 Totalling Dim count As Integer = 0
Totalling is adding together a set of values. To write a program to total you Dim continueLoop As String = "Yes"
need to: While continueLoop = "Yes"
• Initialise the total to 0. Console.WriteLine("Do you want to
• Add the values together (either individually or within a loop). continue?")
continueLoop = Console.ReadLine
Example 1 count = count + 1
Asking the user to enter 10 numbers and totalling them: End While
Total ← 0 Console.WriteLine("You continued " & count-1 &
FOR Counter ← 0 TO 10 " times")
OUTPUT("Enter a number") Python
Total ← Total + INPUT count = 0
NEXT Counter continueInput = "Yes"
OUTPUT("The total is " & Total) while continueInput == "Yes":
VB.NET continueInput = input("Do you want to
Dim total As Integer = 0 continue?")
For counter = 0 To 10 count = count + 1
Console.WriteLine("Enter a number") print("You continued", str(count-1), "times")
total = total + Console.ReadLine Java
Next public static void main(String args[]){
Console.WriteLine("The total is " & total) Scanner scanner = new Scanner(System.in);
Python System.out.println("Enter the first
total = 0 number");
for counter in range(0, 11): Integer count = 0;
total = total + int(input("Enter a number")) String continueInput = "Yes";
print("The total is", total) while(continueInput.equals("Yes")){
System.out.println("Do you want to
Java continue?");
public static void main(String args[]){ continueInput = scanner.nextLine();
Scanner scanner = new Scanner(System.in); count = count + 1;
Integer total = 0; }
for(Integer counter = 0; counter < 11; count = count - 1;
counter++){ System.out.println("You continued " + count
System.out.println("Enter a number"); + " times")
total = total + }
Integer.parseInt(scanner.nextLine()); Example 2
}
System.out.println("The total is " + total); Count how many numbers in an array of 100 elements are more than 50:
} Count ← 0
Example 2 FOR X ← 0 TO 99
IF ArrayData[X] > 50 THEN
Total the data in an array of 100 elements:
Count ← Count + 1
Total ← 0 ENDIF
FOR Count ← 0 TO 99 NEXT X
Total ← Total + ArrayData[Count]
NEXT Count VB.NET
OUTPUT(Total)
Dim arrayData(99) As Integer
VB.NET 'insert code to populate array
Dim total As Integer = 0
Dim arrayData(99) As Integer Dim count As Integer = 0
'insert code to populate array For X = 0 To 99
For count = 0 To 99 If arrayData(X) > 50 Then
total = total + arrayData(count) count = count + 1
Next End If
Console.WriteLine(total) Next
Python Python
total = 0 count = 0
arrayData= [] arrayData=[]
#insert code to populate array #insert code to populate array
for count in range(0, 100): for x in range(0, 100):
total = total + arrayData[count] if arrayData[x] > 50:
print(str(total)) count = count + 1
Java
Java
public static void main(String args[]){ public static void main(String args[]){
Integer total = 0; Integer[] arrayData = new Integer[100];
Integer[] arrayData = new Integer[100]; //insert code to populate array
//insert code to populate array Integer count = 0;
for(Integer count = 0; count < 100; count++) for(Integer x = 0; x < 100; x++){
{ if(arrayData[x] > 50){
total = total + arrayData[count]; count = count + 1;
} }
System.out.println(total); }
} }
Questions
20 What are the two required elements for a totalling program.
8.9 Counting
21 What are the two required elements for a counting program.
Counting is working out how many of something there are. For example how
many numbers were entered that were over 10. To write a program to count 22 Write a program to ask the user to input 100 numbers, total the values
you need to: and output the total.
23 Write a program to ask the user to input numbers. Count how many
• Initialise a counter variable to 0.
numbers are less than 100, and how many are more than or equal to
• Increment (add one to) the counter each time an item is entered, or found. 100. Stop when the user enters the number 0.
Example 1
Count how many numbers the user enters until they say to stop:
Count ← 0
Continue ← "Yes"
WHILE Continue = "Yes" DO
OUTPUT("Do you want to continue?")
INPUT Continue
Count ← Count + 1
ENDWHILE
OUTPUT("You continued " & Count - 1 & " times")
VB.NET
8.10 String manipulation
Dim inputString As String
A string is a piece of text. This could be made up of characters, numbers Console.WriteLine("Enter a string")
and/or symbols. There are lots of different string manipulators that you can inputString = Console.ReadLine
use; these let you alter strings, find values in strings, etc. The two you need to
know are length and substring.
Dim stringlength As Integer
stringlength = Len(inputString)
Length Console.WriteLine(inputString & " is " &
This command will return the number of characters in a string. It has the
stringlength & " characters long")
structure: Python
LENGTH(string). inputString = input("Enter a string")
Example 1 stringLength = len(inputString)
print(inputString, " is ", str(stringLength), "
LENGTH("hi") would return 2. characters long")
VB.NET Java
Dim stringLength As Integer public static void main(String args[]){
stringLength = Len("hi") Scanner scanner = new Scanner(System.in);
Python System.out.println("Enter a string");
stringLength = len("Hi") String inputString = scanner.nextLine();
Integer stringLength = inputString.length();
Java System.out.println(inputString + " is " +
public static void main(String args[]){ stringLength + " characters long");
Integer stringLength = ("hi").length(); }
}
Example 2 Example 4
LENGTH("0123") would return 4. Output the first 4 characters in a string:
VB.NET StringData ← "Goodbye"
Dim stringLength As Integer NewMessage ← SUBSTRING(StringData, 0, 4)
stringLength = Len("0123") OUTPUT(NewMessage)
Python VB.NET
arrayData = [[0] * 50 for i in range(100)] 1 Decompose the problem into its inputs, processes and outputs.
#insert code to populate array 2 Work in pairs to discuss how you will alternate between the players.
searchValue = int(input("Enter a number to 3 Work in pairs to discuss how you will check if a player has won.
search for"))
for row in range(0, 50):
Practice
for column in range(0, 100):
if arrayData[column][row] = searchValue: 1 Write the program to ask each player to make one move. Check that
print("Found it at", str(column), " ", they have not selected the same box, if they have, ask them to select
another box.
str(row))
2 Write an algorithm to check if a player has won and either output who
Java has won, or continue playing.
public static void main(String args[]){
Integer[][] dataArray = new Integer[50] Challenge
[100];
1 Write a function for your algorithm to check if a player has won or not.
Scanner scanner = new Scanner(System.in);
This should check all possible ways of winning and return either: X
Integer searchValue = (crosses has won), O (noughts has won) or C (continue play as no-
Integer.parseInt(scanner.nextLine()); one has won). Your main program will need to decide whether to end,
for(Integer row = 0; row < 50; row++){ or continue based on the value returned.
for(Integer column = 0; column < 100; 2 Edit your program to allow the user to play multiple games. The
column++){ player should alternate allowing noughts to go first, and then crosses
if(dataArray[row][column] == to go first.
searchValue){ 3 Edit your program to allow the user to select how many games they
System.out.println("Found it at " + should play. Keep track of how many games each player has won
column + " " + row); and output who won overall.
}
}
} Questions
} 38 Explain the difference between a variable and an array.
39 Explain why the following code will result in an error.
Example 3 MyData[0] ← 1
Find and output the total of all elements in the each of the first dimensions, in MyData[1] ← 4
an array of 10 elements by 15 elements: MyData[2] ← "7"
FOR Row ← 0 TO 9 MyData[3] ← "9"
Total ← 0 40 Write a program to read 10 numbers from the user into a 1-dimensional
FOR Column ← 0 TO 14 array named MyNumbers.
Total ← Total + TheArray[Row, Column] 41 Write a program to add together all 100 elements in a 1-dimensional
NEXT Column array named MyNumbers.
OUTPUT("Index " & Row & " has the total " &
Total) 42 A 2-dimensional array, MyData, has 20 elements by 5 elements. Write a
function that takes a parameter search value. The function should search
NEXT Row
MyData and return either TRUE if the parameters is in MyData, or
VB.NET FALSE if the parameters is not in MyData.
Dim theArray(9, 14) As Integer
'insert code to populate array
Dim total As Integer = 0
For row = 0 To 9
total = 0
For column = 0 To 14
total = total + theArray(row, column)
Next
Console.WriteLine("Index " & row & " has the
total " & total)
Next
8.16 File handling Java
If you have data in a program, when you stop or close a program all of that public static void main(String args[]){
data is lost. If you need to save data to use again later then you need to save it
externally into a text file. The storage and access of data in a file is called file
String filename = "myNumber.txt";
handling. String theFileData;
try{
COMPUTER SCIENCE IN CONTEXT FileReader f = new FileReader(filename);
BufferedReader reader = new
When playing computer games, for example, on an X-Box or PlayStation, BufferedReader(f);
you are able to save the game and then continue from the same point theFileData = reader.readLine();
next time. It does this by saving data about your current progress in a file. reader.close();
When your program saves, this data is updated; it might store your current }catch(Exception e){
position, health, points, money, etc. When you restart the program, it goes
System.err.println("No file");
to this file and loads the data. This lets you start playing at the exact point
you left it. }
}
Writing to a file
Reading from a file
The specification states that you will only need to write a single item of data or
You need to be able to read a single item of data, or a single line of text. This a line of text. This means you will be overwriting any data that is already in the
means all of the data will be on the first line in the text file, so you do not need file, you do not need to worry about appending (to add onto the end) to data
to check how many lines of text are in the file. Once you have read in the data that already exists, or writing multiple values to the same file.
you can then manipulate it, for example, if it is a line of text you can split it into
individual words, or use it as one item of data. To write a value to a file you need to:
To read a value from a file you need to: • Open the file using its filename (the filename will be a string value).
• Open the file using its filename (the filename will be a string value). • Write the data to the file.
• Close the file.
• Read the data value, and do something with it (e.g. output it, store it in a
variable). You can use the pseudocode commands:
• Close the file. OPEN filename
You can use the pseudocode commands: WRITE data
CLOSE filename
OPEN filename
variable identifier ← READ (filename) Example 1
CLOSE filename Write the word "red" to the file colour.txt:
Example 1 OPEN "colour.txt"
Reading and outputting a word stored in the text file data.txt: WRITE "red"
CLOSE "colour.txt"
OPEN "data.txt"
OUTPUT(READ("data.txt")) VB.NET
CLOSE "data.txt"
Dim fileWrite As New
VB.NET System.IO.StreamWriter("colour.txt")
Dim theFile As New fileWrite.WriteLine("red")
System.IO.StreamReader("data.txt") fileWrite.Close()
Console.WriteLine(theFile.ReadLine()) Python
theFile.Close()
fileData = open("colour.txt",'w')
Python fileData.writelines("red")
theFile = open("data.txt", 'r') fileData.close()
print(theFile.read()) Java
theFile.close()
public static void main(String args[]){
Java try{
public static void main(String args[]){ FileWriter f = new
try{ FileWriter("colour.txt");
FileReader f = new FileReader("data.txt"); BufferedWriter out = new
BufferedReader reader = new BufferedWriter(f);
BufferedReader(f); out.write("red");
System.out.println(reader.readLine()); out.close();
reader.close(); }catch(Exception e){
}catch(Exception e){ System.err.println("No file");
System.err.println("No file"); }
} }
} Example 2
Example 2 Write the number 100 to the file myData.txt storing the filename in a
variable:
Read and output the number stored in the file myNumber.txt by storing the
filename in a variable: Filename ← "myData.txt"
OPEN Filename
Filename ← "myNumber.txt"
WRITE 100
OPEN Filename
CLOSE Filename
TheFileData ← READ(Filename)
CLOSE(Filename) VB.NET
OUTPUT(TheFileData) Dim filename As String = "myData.txt"
VB.NET Dim fileWrite As New
System.IO.StreamWriter(filename)
Dim filename As String = "myNumber.txt" fileWrite.WriteLine(100)
Dim theFileData As String fileWrite.Close()
Dim theFile As New
System.IO.StreamReader(filename) Python
theFileData = theFile.ReadLine() filename = "myData.txt"
theFile.Close() fileData = open(filename,'w')
Console.WriteLine(theFileData) fileData.writelines(100)
Python fileData.close()
filename = "myNumber.txt" Java
theFile = open(filename, 'r') public static void main(String args[]){
theFileData = theFile.read() try{
theFile.close() String filename = "myData.txt";
print(theFileData) FileWriter f = new FileWriter(filename);
BufferedWriter out = new
BufferedWriter(f);
out.write(100);
out.close();
}catch(Exception e){
System.err.println("No file");
}
}
PROGRAMMING TASK 8.5 SUMMARY
A maths quiz game needs to keep a record of the highest number of A variable is a space in memory, with an identifier, that can store a data
points players has gained. The maths quiz is made of randomly generated item that can change while the program is running.
questions; the mathematical operation and the numbers are all randomly
generated. The user keeps on being given new questions until they get A constant is a space in memory, with an identifier, that can store a data
one wrong. The points equate to the number of questions they got correct. item that cannot change while the program is running.
Getting started Integer data type stores whole numbers. Real data type stores decimal
numbers. Char data type stores a single character. String data type
1 In pairs discuss how the program can randomly generate the stores a series of characters. Boolean data type stores True or False.
numbers within reasonable bounds, e.g. between 1 and 20.
Input allows the user to enter data into a system.
2 In pairs discuss how the program can randomly generate the symbol
Output allows the program to display data to the user.
limited to + − / * ^.
There are three constructs in programming; sequence, selection and
3 In pairs discuss how the highest score can be stored in a file. Discuss
iteration.
when the file will be read from, and when it will be written to.
There are two types of selection; IF and CASE.
Practice IF statements can include ELSEIF and ELSE.
1 Write the program to randomly generate one maths question (random There are three types of iteration; count-controlled loops (a set number of
numbers and symbol). Output the question and ask the user for the iterations), pre-condition loops (condition is tested before starting the
answer. Check if it is correct and output an appropriate response. loop) and post-condition loops (condition is tested after completing the
code in the loop).
2 Amend your program to repeatedly ask the user questions until they
get one incorrect. Keep track of how many questions they get correct. Totalling requires initialising the total to 0, then adding the values to it.
3 Amend your program so when the user gets a question incorrect, the Counting requires initialising the count to 0, then adding 1 to it.
current high score is loaded from a text file. Replace the high score if Nested statements are when selection/iteration are within a
the user has more points. selection/iteration construct.
Subroutines are self-contained code, with an identifier that can be called
Challenge from elsewhere in the program.
1 Text files can be read one line at a time. Find out how to store more Subroutines reduce repeated code.
than one high score (e.g. a top-ten) in a file, and rearrange the high- Subroutines can be procedures (that do not return a value) or functions
score table when a user gains a score worthy of including. (that return a value).
A parameter is a value sent to a subroutine.
TIP Library routines contain pre-written and pre-tested subroutines that can
be used in a program.
There are five options so a number could represent each symbol.
A maintainable program includes meaningful identifiers, addition of
comments and subroutines.
REFLECTION An array allows a set of data, of the same data type, to be stored under
one identified.
Consider the program you made for Programming Task 8.5. How did you Each element in an array has an index. This might start at 0 or 1
decide which stage(s) to complete and when to stop? How did you find depending on your language.
example code that you needed? Was this an efficient method of finding
An array can be 1-dimensional (one index) or 2-dimensional (two
the required statements?
indices).
How did you test your program during development? Did you test the
Iteration can be used to read data to, or from an array, by visiting each
program after each line of code, or did you write a section? Did this
index in turn.
method work for the program? Would you do it the same way in the
future? Files can be used to store data once a program has finished running.
How did you test your program once it was complete? Did you set out a
structured test plan with different types of data? Did you ask other people
to help you test it? Was your chosen method appropriate for the program,
or did you have to change it during the testing process?
Questions
43 Why do some programs need to store data in files?
44 What are the three stages that need to be followed to write data to a file?
45 Write a program to read in a value from the file dataStore.txt and
output it.
46 Write a program to ask the user to input a filename, then store the word
"house" in the file.
EXAM-STYLE QUESTIONS SELF-EVALUATION CHECKLIST
After studying this chapter, think about how confident you are with the
1 Programs can use variables and constants.
different topics. This will help you to see any gaps in your knowledge and
a State two similarities between a variable and a constant. [2] help you to learn more effectively.
b State the difference between a variable and a constant. [1] You might find it helpful to rate how confident you are for each of these
[Total: 3] statements when you are revising. You should revisit any topics that you
rated ‘Needs more work’ or ‘Getting there’.
2 Write a program to take two values as input and output first
the result when they are added together, and then the result I can… See Needs Getting Confident
when they are multiplied together. topic more there to move
[4]
work on
3 The following is a pseudocode algorithm.
use variables and constants. 8.1
INPUT Quantity learn about the appropriate use of 8.2
Smallest ← 999 basic data types.
Largest ← 0 write programs that use input and 8.3
Counter ← 0 output.
WHILE Counter < Quantity DO
8.4
INPUT Value
write programs that use sequence, 8.5
Total ← Total + Value
selection and iteration including
IF (Value > Largest) THEN 8.6
nested statements.
Largest ← Value 8.7
ENDIF
IF (Value < Smallest) THEN write programs that use arithmetic, 8.4
logical and Boolean operators.
Smallest ← Value
ENDIF 8.4
Counter ← Counter + 1 write programs that use totalling 8.8
and counting.
ENDWHILE 8.9
OUTPUT("The average is " & Total /
Quantity) write programs that perform the 8.10
OUTPUT("The smallest is " & Smallest & string handling methods.
" and the largest is " & Largest) write programs that use purpose of 8.11
procedures and functions, 8.12
a Identify the type of iteration used in the algorithm. [1] including parameters and variable
scope.
b State the purpose of the variable counter . [1]
write programs using library 8.13
c Give the name of three other variables in the program. [3] routines.
d Re-write the loop using a FOR loop. [5] create maintainable programs. 8.14
[Total: 10] understand the use of arrays (1- 8.15
4 Write a program to ask the user to enter 20 numbers. Store dimensional and 2-dimensional) as
each number in an array. data structures.
[3]
write programs to read data from 8.16
5 Tick one box in each row to identify whether each if statement would
and write data to a file.
result in True, False or is an invalid condition.
[7]
[2]