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

CH 8

This document discusses programming languages and concepts. It notes that while different languages have different syntax rules, they share common fundamental programming concepts like variables, constants, loops, and conditionals. Once a programmer learns these core concepts, they can more easily learn new languages by focusing on syntax differences rather than reinventing programming logic. The document then provides examples of common programming concepts like variables, constants, input/output, and loops written in pseudocode and several common languages to illustrate similarities and differences in syntax.

Uploaded by

DM Coll
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)
81 views

CH 8

This document discusses programming languages and concepts. It notes that while different languages have different syntax rules, they share common fundamental programming concepts like variables, constants, loops, and conditionals. Once a programmer learns these core concepts, they can more easily learn new languages by focusing on syntax differences rather than reinventing programming logic. The document then provides examples of common programming concepts like variables, constants, input/output, and loops written in pseudocode and several common languages to illustrate similarities and differences in syntax.

Uploaded by

DM Coll
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/ 26

PROGRAMMING LANGUAGES

There are lots of different procedural programming languages, for


example, Java, VB.NET, Python, C++ and many, many more. They all
have different commands, requirements for brackets, some need semi-
colons at the end of each line of code. There are, however, a set of
programming fundamentals that work in the same way in most (there are
always one or two that try to be different) languages. Once you know what
these fundamentals are, and how these work, then to program in a new
language you just need to check the syntax which that specific language
uses.

Chapter 8

Programming
IN THIS CHAPTER YOU WILL:

• learn how to write programs using pseudocode


• use variables and constants
• learn about the appropriate use of basic data types
• write programs that use input and output Figure 8.1: Image of a man reading program code
• write programs that use sequence
For example, a FOR loop (a type of countcontrolled loop that you will
• write programs that use arithmetic operators learn about later in the chapter) that will output the numbers 1 to 10.
• write programs that use selection including IF and CASE statements In pseudocode (a generic non-language specific language) this could be:
• write programs that include logical and Boolean operators
FOR Count ← 1 TO 10
• write programs that use iteration including count-controlled, pre- OUTPUT(Count)
condition and post-condition loops
NEXT Count
• write programs that use totalling and counting
• write programs that perform the string handling methods length and
substring
• write programs that use nested statements
• understand the purpose of subroutines These all do the same functions, and they all follow the same principles.
They start with the word ‘for’. They have a variable (count). They set the
• understand the differences between procedures and functions
starting value and they say when to stop. So once you can do a for loop in
• write programs that use subroutines VB.NET, you should just be able to search for how to do it in Python and
• understand the purpose and use of parameters just change a couple of the words.

• write programs with subroutines that take parameters Discussion questions

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

• add features to programs to improve the maintainability


• understand the use of arrays as data structures
• write programs using 1-dimensional arrays
• write programs using 2-dimensional arrays
• understand the need to store data in files
• write programs to read data from a file
• write programs to write data to a file.

GETTING STARTED

Find a computing program (or part of a program) that is written in the


programming language you will be using in-lesson. Work with a friend to
identify what each of the different lines of code do. Present your findings
to the class by showing them each line of code and explaining its purpose.
8.1 Programming concepts Number ← 10
Colour ← "red"
This chapter will introduce different code examples. It will show how to do each
of the procedures in three different languages (Java, VB.NET and Python) and OUTPUT(Number)
pseudocode. The pseudocode (red font) will always appear as the first code in OUTPUT("The colour is ", Colour)
each example. Price ← Number * 2
Variables and constants VB.NET
Dim number As Integer
What are variables and constants?
Dim colour As String = "red"
When you are writing a program, you will need to store data; whether this is Dim price As Single
data that has been input, the result of calculations or any for any other reason. Console.WriteLine(number)
You can store data in variables and constants.
Console.WriteLine("The colour is " & colour)
A computer has memory, e.g. RAM. This is made of lots of spaces where you price = number * 2
can put data. Imagine this table is memory. Each of the boxes can store a
piece of data. Python
colour = "red"
number = input()
print("The colour is", colour)
price = number * 2
Java
public static void main(String args[]){
Integer number = 10;
String colour = "red";
System.out.println("The colour is " +
In memory location 0 is the data 10. In memory location 1 is the data red. colour);
Each variable and constant is one of these spaces in memory that is given an Integer price = number * 2;
identifier (it has a name). In this table the memory numbers have been }
replaced with their identifiers. The memory space with the name number1 is
storing the piece of data 10. Using constants
Before you use a constant in your program you need to give it a value. This is
an assignment statement the same as a variable. (No examples are given for
Python as it does not have in-built constants.)

CONSTANT Colour ← "yellow"


VB.NET
Const colour As String = "yellow"
Java
Variables and constants have one difference. In a variable, you can change the public static void main(String args[]){
data while the program is running. For example, putting the number 30 into final String colour = "yellow";
memory location number1, the memory would then look like this: }
Using the key word constant makes it clear that this value cannot then be
changed.
You get data out of a constant the same way as a variable, by using its
identifier.
OUTPUT(Colour)
VB.NET
Const colour As String = "yellow"
Console.Writeline(colour)
A constant cannot have its value changed while the program is running. When
you declare a constant you put a value into it and this cannot be changed. Java

Using variables public static void main(String args[]){


final String colour = "yellow";
Putting data into a variable is done using an assignment statement. The left
System.out.println(colour);
hand side of the equals sign is the identifier. The right hand side of the equals
sign is the value (see Figure 8.2). }

8.2 Data types


Data in programs can be of different types. For example, it could be numeric or
Figure 8.2: Components of an assignment text. You will need to tell your program what type of data you want it to store.
Some programming languages need you to declare what type of data your
variable will store when you first use it. In some programming languages you
Number ← 10 need to swap data between types, for example, Python will only output string
(text) data, so if you try and output a number without turning it into a string it
Colour ← "red" will produce an error.
Price ← 22.2
Table 8.1 shows common data types:
VB.NET
Data type Description Example data
Dim number As Integer
Dim colour As String String Text – characters numbers and "hello"
Dim price As Single
symbols. "123"
number = 10 The data will always need to be inside "help!"
colour = "red" speech marks, either ' ' or " ".
price = 22.2 Integer Whole numbers. 1
Python 23
number = 10 -300
colour = "red" 45656
price = 22.2 Real, single, Decimal numbers. 1.2
Java
double 23.0
-20.49
public static void main(String args[]){ 3949.3834
Integer number = 10;
String colour = "red"; Boolean Either true or false. TRUE
Double price = 22.2; FALSE
} Char One character or number of symbol. "h"
To get data out of a variable you just use its identifier (see Figure 8.3). The data will always need to be inside "9"
speech marks, either '' or "". "?"

Table 8.1: Common data types

Figure 8.3: Printing the contents of a variable


ACTIVITY 8.1
8.3 Input and output
Take each data type in turn and think of at least 10 different examples of
data that can be stored (apart from Boolean where there can be only two). Output
From these, identify whether any of these could be more than one data A program at some point will probably need to give information to the user. It
type, discuss in pairs what options would be valid and which would be does this using output. When outputting strings (characters, letters, etc.).
most appropriate.
Example 1
Peer Assessment Output the words, Hello World:
Compare your work with another pair. Identify if all of the data is OUTPUT("Hello world")
appropriate for the data type chosen. Discuss the choices, e.g. if one was
VB.NET
more appropriate than the other?
Console.WriteLine("Hello World")
Python
Storing different data types
Storing a string in a variable: print("Hello World!")
Colour ← "red" Java

Storing an integer in a constant:


public static void main(String args[]){
System.out.println("Hello World");
CONSTANT Value ← 10 }
Storing a real number in a variable: Example 2
Price ← 22.4 Output the number 20:
Storing a Boolean in a variable: OUTPUT(20)
Flag ← TRUE VB.NET
VB.NET Console.WriteLine(20)
Dim colour As String = "red" Python
Const value As Integer = 10
print(20)
Dim price As Single = 22.4
Dim flag As Boolean = True Java
public static void main(String args[]){
Python System.out.println(20);
}
colour = "red"
value = 10 If you want to output more than one piece of data then you can join them using
a concatenation symbol. Concatenation means join together, so it joins
price = 22.4 multiple pieces of data together. This could be a comma (,), an ampersand (&)
flag = True or a plus (+) depending on your language. All are acceptable in pseudocode.
Java Example 1
public static void main(String args[]){ Output the word Hello, then the contents of variable name:
String colour = "red";
OUTPUT("Hello ", Name)
final Integer value = 10;
Double price = 22.4; VB.NET
Boolean flag = true; Dim name As String = "Alex"
} Console.WriteLine("Hello " & Name)
Converting between data types Python

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.

2 Write a pseudocode statement to assign the word "house" to a


variable named MyWord.
3 Write a pseudocode statement to declare a constant named
MultiplyValue with the value 10.
In these examples you will see there are spaces within the speech marks. This
is because OUTPUT ("Hello", Name) would join these together, e.g.
8.4 Arithmetic operators
HelloJane. When writing in pseudocode it is not important that these are Arithmetic operators instruct a program to perform calculations. Table 8.2
included, but you might need to do it when outputting in your chosen describes the most common operators, many of which you will know from
programming language. mathematics.

Input Operator Description Example

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

Many of these arithmetic operators should be familiar to you from


mathematics, where you should be used to working out expressions. In Java
programming the same principles are used, you write the formulae but not public static void main(String args[]){
the answer - the computer works that out because the input data can be Integer number1 = 5;
changed. System.out.println("Enter a number");
Scanner scanner = new Scanner(System.in);
Integer number2 =
The operators for DIV and MOD will differ depending on the programming
Integer.parseInt(scanner.nextLine());
language you are using.
Integer result = number1 * number2;
Example 1 }
Taking two numbers as input and adding them together: Example 4
OUTPUT("Enter the first number") Dividing 100 by 5:
INPUT Num1
OUTPUT("Enter the second number") Number1 ← 100
INPUT Num2 Number2 ← 5
Total ← Num1 + Num2 Result ← Number1 / Number2
VB.NET VB.NET

Dim num1 As Integer Dim number1 As Integer = 100


Dim num2 As Integer Dim number2 As Integer = 5
Dim total As Integer Dim result As Single
Console.WriteLine("Enter the first number") result = number2 / number1
num1 = Console.ReadLine Python
Console.WriteLine("Enter the second number") number1 = 100
num2 = Console.ReadLine number2 = 5
total = num1 + num2 result = number2 / number1
Java
Python public static void main(String args[]){
num1 = int(input("Enter the first number")) Double number1 = 100.0;
num2 = int(input("Enter the second number")) Double number2 = 5.0;
total = num1 + num2 Double result = number2 / number1;
}
Java
Example 5
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);, Finding the whole number after dividing 33 by 7:
System.out.println("Enter the first Result ← DIV(33, 7)
number");
VB.NET
Integer num1 =
Integer.parseInt(scanner.nextLine()); Dim result As Single
System.out.println("Enter the second result = 33 7
number"); Python
Integer num2 = result = int(33 / 7)
Integer.parseInt(scanner.nextLine());
Integer total = num1 + num2; Java
} public static void main(String args[]){
Example 2 Integer result = 33 / 7;
}
Subtracting 10 from 20:
Example 6
Number1 ← 10
Finding the remainder after dividing 33 by 7:
Number2 ← 20
Result ← Number2 - Number1 Result ← MOD(33, 7)
VB.NET VB.NET
Dim number1 As Integer = 10 Dim result As Single
Dim number2 As Integer = 20 result = 33 Mod 7
Dim result As Integer Python
result = number2 - number1
result = 33 % 7
Python
Java
number1 = 10
public static void main(String args[]){
number2 = 20
Integer result = 33 % 7;
result = number2 - number1
}
Java
public static void main(String args[]){ Calculations can use parentheses (brackets) to change the order the
Integer number1 = 10; calculations are performed in. The calculations within the brackets are done
first.
Integer number2 = 20;
Integer result = number2 - number1; Example 7
} Total ← 1 + (2 * 3)
Total ← (1 + 2) * 3
Example 3
The first line will result in 7 (3 * 2 = 6 + 1 = 7).
Multiplying two values together:
The second line will result in 9 (1 + 2 = 3 * 3 = 9).
Number1 ← 5
OUTPUT("Enter a number")
INPUT Number2
Result ← Number1 * Number2
VB.NET
Dim number1 As Integer = 5
Dim number2 As Integer
Console.WriteLine("Enter a number")
number2 = Console.ReadLine
Dim result As Integer
result = number2 * number1
Python
number1 = 5
number2 = int(input("Enter a number"))
result = number1 * number2
8.5 Sequence 8.6 Selection
Sequence is the first of three constructs within programs. A sequence is a Selection is the second of the three constructs. In selection a condition is
series of statements that are executed (run) once, in the order they are written. checked and this determines which, if any, code is run. There are two forms of
selection, IF statements and CASE statements.
Example 1
OUTPUT("Enter a colour") Conditions need logical operators. These allow for comparisons to be made.
INPUT Colour Table 8.3 describes these different operators. Each statement using a logical
operator results in TRUE or FALSE.
OUTPUT("Enter your name")
INPUT Name Logical Description Example
OUTPUT(Name , " your favourite colour is " , operator
Colour) = or == Equals to 10 = 10? would give TRUE. 10 is equal to
VB.NET 10.

Dim colour As String 10 = 2? would give FALSE. 10 is not


Console.WriteLine("Enter a colour") equal to 2.
colour = Console.ReadLine() <> or != Not equal to 10 <> 10? would give FALSE. 10 is not,
Dim name As String not equal to 10.
Console.WriteLine("Enter your name")
name = Console.ReadLine() 10 <> 2? would give TRUE. 10 is not
equal to 2.
Console.WriteLine(name & " your favourite
colour is " & colour) < Less than 10 < 11? would give TRUE. 10 is less
Python than 11.
colour = input("Enter a colour") 10 < 10? would give FALSE. 10 is not
name = input("Enter your name") less than 10.
print(name, "your favourite colour is", colour) 11 < 10? would give FALSE. 11 is not
Java less than 10.

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.

Dim valueInput As Integer Value1 ← 10


Console.WriteLine("Enter a number")
Value2 ← 20
valueInput = Console.ReadLine
IF Value1 < Value2 THEN
Dim storedValue As Integer = 100
OUTPUT(Value1)
If valueInput > storedValue Then
ELSE
Console.WriteLine("It is more than 100")
OUTPUT(Value2)
End If
ENDIF
Python
VB.NET
valueInput = int(input("Enter a number"))
Dim value1 As Integer = 10
storedValue = 100
Dim value2 As Integer = 20
if valueInput > storedValue:
If value1 < value2 Then
print("It is more than 100")
Console.WriteLine(value1)
Java Else
public static void main(String args[]){ Console.WriteLine(value2)
Integer storedValue = 100; End If
Scanner scanner = new Scanner(System.in); Python
System.out.println("Enter a number");
value1 = 10
Integer valueInput =
value2 = 20
Integer.parseInt(scanner.
if value1 < value2:
nextLine());
print(value1)
if(valueInput > storedValue){
else:
System.out.println("It is more than 100");
print(value2)
}
} Java

ELSE public static void main(String args[]){


Integer value1 = 10;
This is added within an IF statement. If the IF statement’s condition is false Integer value2 = 20;
then the ELSE will run. You can only ever have one ELSE in an IF if(value1 < value2){
statement. System.out.println(value1);
ELSE follows the structure: }else{
System.out.println(value2);
IF comparison THEN }
Statements that run if the comparison is }
true ELSEIF
ELSE
Statements that run if the comparison is This allows for a second condition to be used within the same IF statement. If
false the first condition is False, then a second condition can be checked.
ENDIF ELSEIF follows the structure:
IF comparison1 THEN
Statements that run if the comparison is
true
ELSEIF comparison2 THEN
Statements that run if comparison1 is false,
and comparison2 is true
ENDIF
Example 1 Example 3
This will output which number is greater, or nothing will output if they are the This uses multiple ELSEIFs.
same.
IF Age < 14 THEN
Num1 ← 10 OUTPUT("You are not old enough")
Num2 ← 20 ELSEIF Age < 16 THEN
IF Num1 < Num2 THEN OUTPUT("You need an adult present")
OUTPUT(Num2) ELSEIF
ELSEIF Num2 < Num1 THEN
VB.NET
OUTPUT(Num1)
ENDIF Dim age As Integer
Console.WriteLine("Enter your age")
VB.NET
age = Console.ReadLine
Dim num1 As Integer = 10 If age < 14 Then
Dim num2 As Integer = 20 Console.WriteLine("You are not old enough")
If num1 < num2 Then ElseIf age < 16 Then
Console.WriteLine(num2) Console.WriteLine("You need an adult
ElseIf num2 < num1 Then present")
Console.WriteLine(num1) End If
End If Python
Python age = int(input("Enter your age"))
num1 = 10 if age < 14:
num2 = 20 print("You are not old enough")
if num1 < num2: elif age < 16:
print(num2) print("You need an adult present")
elif num2 < num1:
print(num1) SELECT CASE
Java A SELECT CASE statement allows the program to take one variable or
value, and then have lots of different options depending what it is equal to.
public static void main(String args[]){
Integer num1 = 10; CASE follows the structure:
Integer num2 = 20; CASE OF variable
if(num1 < num2){ value1:
System.out.println(num2); Statements that run if CASE value1 is true
}else if(num2 < num1){ value2:
System.out.println(num2); Statements that run if CASE value1 is
} false, and value2 is true
} OTHERWISE
You can use multiple ELSEIF statements, and combine them with a single Statements that run if none of the
ELSE statement at the end. comparisons are true.
ENDCASE
This will follow the structure:
IF comparison1 THEN
A case can have as many CASE statements as needed, but can only ever
Statements that run if the comparison is have a maximum of one default (this runs if none of the comparisons are true).
true
ELSEIF comparison2 THEN Example 1
Statements that run if comparison1 is false, Using a SELECT CASE to output a grade for an in-lesson test. (No example
and comparison2 is true is given for Python as it does not have a CASE construct and no example is
….as many ELSEIFs as you need given for Java as it does not support switch statements with comparisons, e.g.
ELSE < or >.)
Statements that run if none of the Score ← INPUT("Enter score")
comparisons are true CASE OF score:
ENDIF >=80: OUTPUT ("A")
Example 2 >=70: OUTPUT("B")
>=60: OUTPUT("C")
This uses ELSEIF and an ELSE to output the largest number.
>=50: OUTPUT("D")
IF Num1 > Num2 THEN OTHERWISE OUTPUT("U")
OUTPUT(Num1) ENDCASE
ELSEIF Num2 > Num1 THEN VB.NET
OUTPUT(Num2)
ELSE Dim score As Integer
OUTPUT("They are the same") Console.WriteLine("Enter score")
ENDIF score = Console.ReadLine
Select Case score
VB.NET Case >= 80
Dim num1 As Integer = 10 Console.WriteLine("A")
Dim num2 As Integer = 20 Case >= 70
If num1 > num2 Then Console.WriteLine("B")
Console.WriteLine(num1) Case >= 60
ElseIf num2 > num1 Then Console.WriteLine("C")
Console.WriteLine(num2) Case >= 50
Else Console.WriteLine("D")
Console.WriteLine("They are the same") Case Else
End If Console.WriteLine("U")
End Select
Python
Example 2
num1 = 10
num2 = 20 Output a message depending on which number is entered. (No example is
given for Python as it does not have a CASE construct.)
if num1 > num2:
print(num1) OUTPUT("Enter a number, 1 to 5")
elif num2 > num1: INPUT Choice
print(num2) CASE OF Choice:
else: 1: OUTPUT("Menu option 1")
print("They are the same") 2: OUTPUT("Menu option 2")
Java
3: OUTPUT("Menu option 3")
4: OUTPUT("Menu option 4")
public static void main(String args[]){ 5: OUTPUT("Menu option 5")
Integer num1 = 10; OTHERWISE OUTPUT("Invalid choice")
Integer num2 = 20; ENDCASE
if(num1 < num2){
System.out.println(num2);
}else if(num2 < num1){
System.out.println(num2);
}else{
System.out.println("They are the same");
}
}
VB.NET
Dim choice As Integer ACTIVITY 8.3
Console.WriteLine("Enter a number, 1 to 5") Make a list of the use of AND, OR and NOT in real-life situations. For
choice = Console.ReadLine example, if one of two light switches is pressed then a light turns on. If the
Select Case choice door is locked and you have the key then you can unlock the door.
Case 1
Console.WriteLine("Menu option 1") Peer Assessment
Case 2
Share your list in groups of 3. Discuss each of the statements and
Console.WriteLine("Menu option 2") whether they have been correctly identified as AND, OR or NOT. Select
Case 3 one of each Boolean operator and share it with the rest of the class.
Console.WriteLine("Menu option 3")
Case 4
Console.WriteLine("Menu option 4") Example 1
Case 5 This will output the first message if both test marks are greater than or equal to
Console.WriteLine("Menu option 5") 90. If only one mark is greater than or equal to 90 then the second message
Case Else will output.
Console.WriteLine("Invalid choice") OUTPUT("Enter the mark for test 1")
End Select INPUT Mark1
Java OUTPUT("Enter the mark for test 2")
INPUT Mark2
public static void main(String args[]){ IF Mark1 >= 90 AND Mark2 >= 90 THEN
Scanner scanner = new Scanner(System.in); OUTPUT("Well done you got top marks on both
System.out.println("Enter a number, 1 to tests")
5"); ELSEIF Mark1 >= 90 OR Mark2 >= 90 THEN
Integer choice= OUTPUT("Well done you got top marks on one
Integer.parseInt(scanner.nextLine()); of the tests")
switch(choice){ ELSE
case 1: OUTPUT("You didn't quite get top marks on
System.out.println("Menu option 1"); the tests, try again next time")
break; ENDIF
case 2:
System.out.println("Menu option 2"); VB.NET
break; Dim mark1 As Integer
case 3: Console.WriteLine("Enter the mark for test 1")
System.out.println("Menu option 3"); mark1 = Console.ReadLine
break; Dim mark2 As Integer
case 4: Console.WriteLine("Enter the mark for test 2")
System.out.println("Menu option 4"); mark2 = Console.ReadLine
break; If mark1 >= 90 And mark2 >= 90 Then
case 5: Console.WriteLine("Well done you got top
System.out.println("Menu option 5"); marks on both tests")
default: ElseIf mark1 >= 90 Or mark2 >= 90 Then
System.out.println("Invalid choice"); Console.WriteLine("Well done you got top
} marks on one test")
} Else
Console.WriteLine("You didn't quite get top
ACTIVITY 8.2 marks ont he tests, try again next time")
End If
What is the difference between IF and CASE statements? Is there a
Python
scenario when one is more appropriate than another? Write one example
of each where that is the most appropriate type to use. mark1 = input("Enter the mark for test 1")
mark2 = input("Enter the mark for test 2")
Peer Assessment if mark1 >= 90 and mark2 >= 90:
Explain your choices in Activity 8.2 to a partner. Did they come to the
print("Well done you got top marks on both
same conclusions as you did? Is there always a correct answer or are the tests")
different points of view all valid? elif mark1 >= 90 or mark2 >= 90:
print("Well done you got top marks on one of
the tests")
Boolean Operators else:
There are three Boolean operators that you can use to join conditions: the print("You didn't quite get top marks on the
AND operator, the NOT operator and the OR operator. These are described tests, try again next time")
in Table 8.4.
Java
Boolean Description Example
operator public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
AND If both conditions are IF 1 = 1 AND 2 = 2
true, the result is true. System.out.println("Enter the mark for test
This will return TRUE. The left of the AND is 1");
If one or both true, and the right of the AND is true. Integer mark1 =
conditions are false,
the result is false. IF 1 = 1 AND 1 > 2 Integer.parseInt(scanner.nextLine());
System.out.println("Enter the mark for test
This will return FALSE. The left of AND is 2");
true, but the right of AND is false. Integer mark2 =
IF 1 < -2 AND 0 < -1 Integer.parseInt(scanner.nextLine());
This will return FALSE. Both comparisons
if(mark1 >= 90 && mark2 >= 90){
are false, so the result is false. System.out.println("Well done you got top
marks on both tests");
OR If one, or both, IF 1 = 1 OR 2 = 2 }else if(mark1 >= 90 || mark2 >= 90){
conditions are true,
This will return TRUE. The left of the OR is System.out.println("Well done you got top
the result is true. marks on one of the tests");
true, and the right of the OR is true.
If both conditions are }else{
false, the result is IF 1 = 1 OR 1 > 2 System.out.println("You didn't quite get
false. This will return TRUE. The left of OR is true, top marks on the tests, try
but the right of OR is false. again next time");
IF 1 < -2 OR 0 < -1 }
}
This will return FALSE. Both comparisons
are false, so the result is false.

NOT Reverse the IF NOT(1 = 1)


condition. If the
condition is True it The brackets equal to TRUE, 1 equals 1.
becomes False. The NOT makes it FALSE, so it becomes 1
does not equal 1.
IF NOT (End of File)
This is used with file handing. End of
File will return TRUE if there is no data left
in the file. The NOT turns this to false. So
while not at the end of the file.

Table 8.4: Boolean operators


Example 2
Questions
Output the highest number out of three that are input:
8 Describe what is meant by selection.
OUTPUT("Enter 3 numbers")
INPUT Number1 9 Identify the two different examples of selection.
INPUT Number2 10 Write a program that takes two numbers as input and outputs the largest.
INPUT Number3 11 Write a program that outputs a question (e.g. a maths question), takes an
IF Number1 > Number2 AND Number1 > Number3 THEN answer from a user and outputs if they are correct or not.
OUTPUT(Number1) 12 Ask the user to input a colour. The program should then output a different
ELSEIF Number2 > Number3 THEN message if the user enters the word "yellow", "green" or
OUTPUT(Number2) "blue". If neither of these are entered, the program should output a
ELSE different message. Use a CASE statement.
OUTPUT(Number3)
ENDIF
VB.NET 8.7 Iteration
Dim number1 As Integer An iteration or loop is a programming construct where statements are run
Console.WriteLine("enter a number") either a finite number of times, until a condition is true or while a condition is
number1 = Console.ReadLine() true.
Dim number2 As Integer There are three types of loop: count-controlled, pre-condition and post-
Console.WriteLine("enter a number") condition.
number2 = Console.ReadLine
Dim number3 As Integer Count-controlled
Console.WriteLine("enter a number") This type of loop uses a counter to run a set number of times. The most
number3 = Console.ReadLine common count-controlled loop is the for loop. This has the structure:
If number1 > number2 And number1 > number3 Then FOR variable ← start value TO endvalue
Console.WriteLine(number1) Code that runs repeatedly
ElseIf number2 > number3 Then NEXT variable
Console.WriteLine(number2)
The loop will run from the start value to the end value, increasing by 1 each
Else
time. If the start value is 1 and the end value is 10, it will run 10 times (1, 2, 3,
Console.WriteLine(number3) 4, 5, 6, 7, 8, 9 and 10).
End If
Example 1
Output the numbers 1 to 10:
Python
FOR X ← 1 TO 10
number1 = input("Enter a number") OUTPUT(X)
number2 = input("Enter a number") NEXT X
number3 = input("Enter a number")
VB.NET
if number1 > number2 and number1 > number3:
print(number1) For x = 1 To 10
elif number2 > number3: Console.WriteLine(x)
print(number2) Next
else: Python
print(number3)
for x in range(1, 11):
Java print(x)
public static void main(String args[]){ Java
Scanner scanner = new Scanner(System.in);
public static void main(String args[]){
System.out.println("Enter a number");
for(Integer x = 1; x <= 10; x++){
Integer number1 =
System.out.println(x);
Integer.parseInt(scanner.nextLine());
}
System.out.println("Enter a number");
}
Integer number2 =
Integer.parseInt(scanner.nextLine()); Example 2
System.out.println("Enter a number"); Output the 12 times table from 1 to 12:
Integer number3 =
FOR Count ← 1 TO 12
Integer.parseInt(scanner.nextLine());
OUTPUT(Count * 12)
if(number1 > number2 && number1 > number3){
NEXT Count
System.out.println(number1);
}else if(number2 > number3){ VB.NET
System.out.println(number2); For count = 1 To 12
}else{ Console.WriteLine(count * 12)
System.out.println(number3); Next
}
Python
}
for count in range (1, 13):
PROGRAMMING TASK 8.2 print(count * 12)
A computer program needs writing to act as a calculator. The program Java
should take in two values and a symbol (e.g. +, −, * or /). Depending on public static void main(String args[]){
the symbol entered, the calculator should perform that calculation. For for(Integer count = 1; count < 13; count++){
example, if 3 5 + is entered, then the result should be 8 (3 + 5 = 8). System.out.println(count * 12);
Getting started }
1 Identify the inputs that the system will require. }
2 Identify appropriate variables to store the inputs in.
3 Write a program to ask the user to enter the two numbers and
symbol, and store these in variables.

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.

Example 1 3 In pairs plan the algorithm to perform the required tasks.

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

stringLength = len("0123") Dim stringData As String = "Goodbye"


Dim newMessage As String
Java
newMessage = Mid(stringData, 1, 4)
public static void main(String args[]){ Console.WriteLine(newMessage)
Integer stringLength = ("0123").length(); Python
}
stringData = "Goodbye"
Substring newMessage = stringData[0:4]
This command will return some of the characters in the string. It has the print(newMessage)
structure: Java
SUBSTRING(string, start character, number of public static void main(String args[]){
characters). String stringData = "Goodbye";
Depending on your language, the first character could be in position 0 or String newMessage =
position 1. stringData.substring(0,4);
System.out.println(newMessage);
Example 1
}
Using substring:
Example 5
SUBSTRING("Hello", 0, 1) This will start at character 0 and take 1
character. Output each letter of a string one character at a time. Depending on your
language, the stopping condition might be the length, or the length −1
It will return "H".
depending on whether the first character is 0 or 1.
VB.NET
OUTPUT("Enter a message")
(Uses 1 for the first character.) INPUT StringInput
Dim substring As String FOR Count ← 0 to LENGTH(StringInput) - 1
substring = Mid("Hello", 1, 1) Character ← SUBSTRING(StringInput, Count, 1)
Python OUTPUT(Character)
NEXT Count
(Uses 0 for the first character.)
VB.NET
substring = "Hello"[0:1]
print(substring) Dim stringInput As String
Console.WriteLine("Enter a message")
stringInput = Console.ReadLine
Java Dim character As String
public static void main(String args[]){ For count = 1 To Len(stringInput)
String substring = ("Hello").substring(0,1); character = Mid(stringInput, count, 1)
System.out.println(substring); Console.WriteLine(character)
} Next
Example 2 Python
Using substring: stringInput = input("Enter a message")
for count in range(0, len(stringInput)):
SUBSTRING("Goodbye", 4, 3). This will start at character 4 and take
character = stringInput[count:count+1]
3 characters. It will return "bye".
print(character)
VB.NET
Java
Dim substring As String
public static void main(String args[]){
substring = Mid("Goodbye", 5, 3)
Scanner scanner = new Scanner(System.in);
Python System.out.println("Enter a message");
substring = "Goodbye"[4:7] String stringInput = scanner.nextLine();
Java
String character;
for(Integer count = 0; count <
public static void main(String args[]){ stringInput.length(); count++){
String substring = ("Goodbye").substring(5, character = stringInput.substring(count,
3); count+1);
} System.out.println(character);
}
Example 3 }
Output the length of a string that the user inputs:
InputString ← INPUT("Enter a string")
StringLength ← LENGTH(InputString)
OUTPUT(InputString & " is " & StringLength & "
characters long")
Example 6
Output the last 3 characters in a string:
MoreThan10 ← 0
OUTPUT("Enter a message") EqualTo10 ← 0
INPUT StringInput FOR X ← 0 TO 99
NewString ← SUBSTRING(StringInput, OUTPUT("Enter a number")
LENGTH(StringInput) - 3, 3) INPUT Number
OUTPUT(NewString) IF Number > 10 THEN
VB.NET MoreThan10 ← MoreThan10 + 1
Dim stringInput As String ELSEIF Number = 10 THEN
Console.WriteLine("Enter a message") EqualTo10 ← EqualTo10 + 1
stringInput = Console.ReadLine ENDIF
Dim newString As String NEXT X
newString = Mid(stringInput, Len(stringInput) - This code has an IF statement nested inside a count-controlled loop.
2, 3) VB.NET
Console.WriteLine(newString)
Dim moreThan10 As Integer = 0
Python Dim equalTo10 As Integer = 0
stringInput = input("Enter a message") Dim number As Integer
newString = stringInput[len(stringInput)-3:] For x = 0 To 99
print(newString) Console.WriteLine("Enter a number")
Java number = Console.ReadLine
If number > 10 Then
public static void main(String args[]){ moreThan10 = moreThan10 + 1
Scanner scanner = new Scanner(System.in); ElseIf number = 10 Then
System.out.println("Enter a message"); equalTo10 = equalTo10 + 1
String stringInput = scanner.nextLine(); End If
String newString = Next
stringInput.substring(stringInput.length()-3,
stringInput.length()); Python
System.out.println(newString); moreThan10 = 0
} equalTo10 = 0
for x in range(0, 100):
Upper and lower number = int(input("Enter a number"))
The characters a–z can be converted into uppercase and the characters A–Z if number > 10:
can be converted into lowercase. This can be done to an individual character, moreThan10 = moreThan10 + 1
or to an entire string at the same time. If a character is already in upper case, elif number = 10:
trying to convert it to upper case will not change it. equalTo10 = equalTo10 + 1
UPPER(string) Java
LOWER(string)
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
Example 1 Integer moreThan10 = 0;
Using UPPER with a string: Integer equalTo10 = 0;
for(Integer x = 0; x < 100; x++){
UPPER("Hello") will return "HELLO" System.out.println("Enter a number");
VB.NET Integer number =
Word = "Hello".toUpper() Integer.parseInt(scanner.nextLine());
if(number > 10){
Python
moreThan10 +=1;
Word = "Hello".upper() }else if(number == 10){
Java equalTo10 +=1;
}
Word = "Hello".toUpperCase();
}
Example 2 }
Using LOWER with a string stored in a variable: Example 2
Word ← "HELLO" Loop counting how many values in an array are more than or equal to 100, and
Word ← LOWER(Word) then stop counting:
VB.NET Number ← 0
word = "HELLO" Count ← 0
word = word.toLower() WHILE Number < 10 DO
DataInArray ← ArrayData[Count]
Python
Count ← Count + 1
word = "HELLO" IF DataInArray >= 100 THEN
word = word.lower() Number ← Number + 1
Java ENDIF
word = "HELLO"; ENDWHILE
word = word.toLowerCase(); This has an IF statement inside a pre-condition loop.
VB.NET
COMPUTER SCIENCE IN CONTEXT
Dim number As Integer = 0
When you need to create a password for a website or computer there are Dim count As Integer = 0
usually rules you have to follow; e.g. more than 8 characters, at least one Dim dataArray(999) As Integer
lowercase letter, at least one uppercase letter, one special character, etc. 'insert code to populate array
The length function you have just learnt can be used to work out if the
password is long enough. You can also use the substring function by Dim dataInArray As Integer
checking each character one at a time to work out if it is a special While number < 10
character (e.g. / ! ?, etc.). You don’t need to know about cases for the
specification, but you can research how to find out about a character in
dataInArray = dataArray(count)
upper case, or lowercase as well. Put them all together and you can write count = count + 1
a program to check if a password is valid. If dataInArray >= 100 Then
number = number + 1
End If
End While
8.11 Nested statements Python
A nested statement is one or more selection and/or iteration statements arrayData = []
inside another selection/iteration statement. This could be an IF statement #insert code to populate array
inside an IF statement or a loop inside an IF statement or an IF statement in a number = 0
loop or a loop within a loop. You might have already used these without count = 0
realising they were called nested statements.
while number < 10:
The position of the start and end of these constructs are important. If, for dataInArray = arrayData[count]
example, a loop starts inside an IF statement, the loop must also finish inside count = count + 1
the same IF statement.
if dataInArray >= 100:
Example 1 number = number + 1
Count how many numbers entered are more than 10, and how many are equal
to 10:
Java
8.12 Subroutines
public static void main(String args[]){
Integer[] dataArray = new Integer[1000]; A subroutine is a self-contained piece of code that has an identifier (name),
//insert code to populate array and it can be called from anywhere in the main program.
Integer number = 0; When you decompose a problem into sub-systems, each of the sub-systems
Integer count = 0; can be written as an individual subroutine. You can then call that subroutine
Integer dataInArray = 0; when you need to use it.
while(number < 10){ Subroutines are useful because they reduce code. You write the subroutine
dataInArray = dataArray[count]; once, and then you can call it as many times as you need to, instead of having
count +=1; to re-write it every time. Each time you re-write it there is a chance of an error,
so this reduces the chances of this error.
if(dataInArray >= 100){
number +=1; There are two types of subroutine: procedures and functions. A function
} returns a value to the program that called it. A procedure does not return a
} value.
} Procedures and functions can both take one or more values as parameters.
These are values that are sent to the subroutine. Parameters will be introduced
Example 3 after the basics of procedures and functions.
Output only the vowels in a message input if user selects option 1:
Procedures
OUTPUT("Enter 1 or 2")
INPUT Choice A procedure runs the code inside it, and does not return a value. The structure
of a procedure is:
IF Choice = 1 THEN
OUTPUT("Enter a word") PROCEDURE identifier()
INPUT Word code to run inside the function
FOR Count ← 0 to LENGTH(Word)-1 ENDPROCEDURE
Character ← SUBSTRING(Word, Count, 1) The identifier is then used in the main program.
IF Character = "a" OR Character = "e" OR Example 1
Character = "I"
OR Character = "o" OR Character = "u" A procedure to output the numbers 1 to 10:
THEN PROCEDURE Output1To10()
OUTPUT(Character) FOR Count ← 1 to 10
ENDIF OUTPUT(Count)
NEXT Count NEXT Count
ENDIF ENDPROCEDURE
This has a FOR loop inside an IF, and another IF inside the FOR loop. The main program can then call the procedure with the code:
VB.NET Output1To10()
Dim choice As Integer VB.NET
Console.WriteLine("Enter 1 or 2") Sub Main()
choice = Console.ReadLine output1To10()
Dim word As String End Sub
Dim character As String Sub output1To10()
If choice = 1 Then For count = 1 To 10
Console.WriteLine("Enter a word") Console.WriteLine(count)
word = Console.ReadLine Next
For count = 0 To Len(word) End Sub
character = mid(word, count, 1)
If character = "a" Or character = "e" Or Python
character = "i" Or character = def output1To10():
"o" Or character = "u" Then for count in range(1, 11):
Console.WriteLine(character) print(str(count))
End If output1To10()
Next Java
End If
public static void output1To10(){
Python for(Integer count = 0; count < 11; count++){
choice = int(input("Enter 1 or 2")) System.out.println(count);
if choice == 1: }
word = input("Enter a word") }
for count in range(0, len(word)): public static void main(String args[]){
character = word[count:count+1] output1To10();
if character == "a" or character == "e" or }
character == "i" or character
== "o" or character == "u": Example 2
print(character) A procedure to take two numbers from the user and multiply then together:
Java PROCEDURE Multiply()
public static void main(String args[]){ OUTPUT("Enter a number")
Scanner scanner = new Scanner(System.in); INPUT Num1
System.out.println("Enter 1 or 2"); OUTPUT("Enter a second number")
String word; INPUT Num2
String character; Total ← Num1 * Num2
Integer choice = ENDPROCEDURE
Integer.parseInt(scanner.nextLine()); The procedure can be called in the main program with the code:
if(choice == 1){
System.out.println("Enter a word"); multiply()
word = scanner.nextLine(); VB.NET
for(Integer count = 0; count < Sub Main()
word.length(); count++){ multiply()
character = word.substring(count, count End Sub
+ 1) Sub multiply()
if(character.equals("a") || Dim num1 As Integer
character.equals("e") || character. Console.WriteLine("Enter a number")
equals("i") || character.equals("o") num1 = Console.ReadLine
|| character.equals("u")){ Dim num2 As Integer
System.out.println(character); Console.WriteLine("Enter a second number")
} num2 = Console.ReadLine
} Dim total As Integer
} total = num1 * num2
} End Sub
Questions Python
24 Give one example of a nested statement. def multiply():
25 What will the pseudocode statement LENGTH("Hello World!") num1 = int(input("Enter a number"))
return? num2 = int(input("Enter a second number"))
26 What will the pseudocode statement SUBSTRING("HELLO
total = num1 * num2
WORLD!", 6, 5) return? multiply()
27 Write a program to take a string input from the user, count out how many
numbers are in the string and output the count.
28 Write a program to output a string value backwards.
Java
Example 2
public static void multiply(){
Write a function to total all the values in an array with 50 elements and then
Scanner scanner = new Scanner(System.in);
return the total:
System.out.println("Enter a number");
Integer num1 = FUNCTION TotalValues()
Integer.parseInt(scanner.nextLine()); Total ← 0
System.out.println("Enter a number"); FOR X ← 0 TO 49
Integer num2 = Total ← Total + Array[X]
Integer.parseInt(scanner.nextLine()); NEXT X
Integer total = num1 * num2; RETURN Total
} ENDFUNCTION
public static void main(String args[]){ To store the return value in a variable in the main program:
multiply();
} Total = TotalValues()
VB.NET
Function
Sub Main()
A function returns a value to the program that called it. This can be by either Dim total As Integer
using the RETURN command, or saving a value to the function’s identifier. total = totalValues()
Once a value is returned, the function stops running, so it cannot have any End Sub
code after otherwise this will not run.
Function totalValues()
It has the structure: Dim arrayData(49) As Integer
FUNCTION identifier() 'insert code to populate array
Code to run in the function Dim total As Integer = 0
RETURN value For x = 0 To 49
ENDFUNCTION total = total + arrayData(x)
Next
When the function is called it returns a value, so something needs to happen
with this value. It could be output, e.g. Return total
End Function
OUTPUT(function identifier)
Python
or it could be saved in a variable, e.g.
def totalValues():
arrayData = []
Function #insert code to populate array
A function returns a value to the program that called it. This can be by either total = 0
using the RETURN command, or saving a value to the function’s identifier. for x in range(0, 50):
Once a value is returned, the function stops running, so it cannot have any total = total + arrayData[x]
code after otherwise this will not run. return total
It has the structure:
FUNCTION identifier() total = totalValues()
Code to run in the function
Java
RETURN value
ENDFUNCTION public static Integer totalValues(){
Integer[] arrayData = new Integer[50];
When the function is called it returns a value, so something needs to happen
with this value. It could be output, e.g.
//insert code to populate array
Integer total = 0;
OUTPUT(function identifier) for(Integer x = 0; x < 50; x++){
or it could be saved in a variable, e.g. total = total + arrayData[x];
variable identifier = function identifier }
return total;
Example 1 }
Write a function to ask the user to enter two values, add them together and public static void main(String args[]){
return the value: Integer total = totalValues();
FUNCTION Multiply() }
OUTPUT("Enter a number")
INPUT Num1
Scope
OUTPUT("Enter another number") The scope of a variable is the areas within a program that it can be accessed.
INPUT Num2 There are two scopes: global and local.
RETURN Num1 * Num2 If you declare a variable (or constant, or array) as global then it means it can
ENDFUNCTION be accessed by any part of the program. That includes the main program and
any subroutines. In most languages this means declaring it at the top of the
To output the return value the main program can use: program.
OUTPUT(Multiply()) Example 1
VB.NET Declaring a global variable, then outputting its value twice. Once in the main
Sub Main() program, and once in a procedure call call.
Console.WriteLine(multiply()) GLOBAL Data
End Sub PROCEDURE OutputData()
Function multiply() OUTPUT(Data)
Dim num1 As Integer ENDPROCEDURE
Console.WriteLine("Enter a number") //main program
num1 = Console.ReadLine Data ← 1
Dim num2 As Integer OUTPUT(Data)
Console.WriteLine("Enter a second number") OutputData()
num2 = Console.ReadLine
VB.NET
Return num1 * num2
End Function Module Program
Python
Dim data As Integer
Sub outputData()
def multiply(): Console.WriteLine(data)
num1 = int(input("Enter a number")) End Sub
num2 = int(input("Enter another number")) Sub Main(args As String())
return num1 * num2 data = 1
print(str(multiply())) Console.WriteLine(data)
Java outputData()
public static Integer multiply(){ End Sub
Scanner scanner = new Scanner(System.in); End Module
vSystem.out.println("Enter a number");
Integer num1 =
Integer.parseInt(scanner.nextLine());
System.out.println("Enter a second number");
Integer num2 =
Integer.parseInt(scanner.nextLine());
return(num1 * num2);
}
public static void main(String args[]){
System.out.println(multiply());
}
Python Example 1
data = 1 A function takes two numbers, divides them and returns the result:
def outputData(): FUNCTION Division(First, Second)
print(str(data)) RETURN First / Second
print(str(data)) ENDFUNCTION
outputData() The main program sends 10 and 2, then outputs the return value.
Java OUTPUT(Division(10, 2))
class outputting{ VB.NET
static Integer data = 1;
public static void outputData(){ Sub Main()
System.out.println(data); Console.WriteLine(division(10, 2))
} End Sub
public static void main(String args[]){ Function division(first, second)
System.out.println(data); Return first / second
outputData(); End Function
} Python
} def division(first, second):
return first / second
If you declare a variable (or constant, or array) as local, then it can only be
accessed in the part of the code where it is declared. If you declare it first in a print(str(division(10,2)))
subroutine, then it can only be accessed within that subroutine. If you declare it Java
in the main program, it can only be accessed in the main program.
public static Double division(Double first,
Example 2 Double second)
Creating a local variable to the main program and outputting it twice. Once in {
the main program, and once from a subroutine where it is sent as a parameter. return (first / second);
PROCEDURE OutputData(DataParameter) }
OUTPUT(DataParameter) public static void main(String args[]){
ENDPROCEDURE System.out.println(division(10.0,2.0));
Data ← 1 }
OUTPUT(DataParameter)
OutputData(Data) Example 2
VB.NET A procedure takes 2 values and outputs all the numbers between the first
number to the second:
Module Program
Sub outputData(dataParameter) PROCEDURE OutputNumbers(Num1, Num2)
Console.WriteLine(dataParameter) FOR Count ← Num1 TO Num2
End Sub OUTPUT Count
Sub Main(args As String()) NEXT Count
Dim data As Integer ENDPROCEDURE
data = 1 The main program taking two values from the user.
Console.WriteLine(data) OUTPUT("Enter the smallest number")
outputData(data) INPUT FirstNumber
End Sub OUTPUT("Enter the largest number")
End Module INPUT SecondNumber
Python OutputNumbers(FirstNumber, SecondNumber)
def outputData(dataParameter): VB.NET
print(str(dataParameter)) Sub Main()
#main Console.WriteLine("Enter the smallest
data = 1 number")
print(str(data)) Dim firstNumber As Integer =
outputData(data) Console.ReadLine
Java Console.WriteLine("Enter the largest
class outputting{ number")
public static void outputData(Integer Dim secondNumber As Integer =
dataParameter){ Console.ReadLine
System.out.println(dataParameter); outputNumbers(firstNumber, secondNumber)
} End Sub
public static void main(String args[]){ Sub outputNumbers(num1, num2)
Integer data = 1; For count = num1 To num2
System.out.println(data); Console.WriteLine(count)
outputData(data); Next
} End Sub
} Python
def outputNumbers(num1, num2):
for count in range(num1, num2+1):
Best practice restricts the use of global variables, because their memory is
taken for the whole of the program and nothing else can use that memory print(str(count))
space. If you declare them locally then when that part of the program finishes
the memory location is freed. Local variables are more tricky to program firstNumber = int(input("Enter the smallest
because you need to send them as parameters between functions and make number"))
sure you return them back if they have changed. secondNumber = int(input("Enter the largest
number"))
Parameters outputNumbers(firstNumber, secondNumber)
A parameter is a value that is sent from the main program to the subroutine Java
(procedure or function). Parameters are declared inside the brackets after the
subroutines name, e.g. public static void outputNumbers(Integer num1,
Integer num2){
PROCEDURE identifier(parameter1, parameter2 …) for(Integer count = num1; count <= num2;
ENDPROCEDURE count++){
or System.out.println(count);
FUNCTION identifier(parameter1, parameter2 …) }
ENDFUNCTION }
public static void main(String args[]){
If a subroutine is declared with parameters, then it must be called with the
Scanner scanner = new Scanner(System.in);
same number of parameters. For example:
System.out.println("Enter the smallest
PROCEDURE Total(Num1, Num2) number");
ENDPROCEDURE Integer firstNumber =
This has two parameters. When the procedure is called it must have 2 Integer.parseInt(scanner.nextLine());
numbers sent to it. This could be numbers, e.g. System.out.println("Enter the largest
Total(1,2) number");
Integer secondNumber
or variables. e.g.
=Integer.parseInt(scanner.nextLine());
Total(Number1, Number2) outputNumbers(firstNumber, secondNumber);
}
Questions 8.14 Maintainable programs
29 What is the difference between a function and a procedure? When you write a program there are several things to take into consideration to
30 Consider the following function: make it a maintainable program. This is so that when you come back to it in a
week, or a year, you can still understand what all of the code does. It might be
FUNCTION Calculate(Num1, Num2) you are writing a program that someone else needs to understand, so you
Num1 ← Num1 * 2 need to make it understandable to someone who does not know what the
Num2 ← Num2 + Num1 program does.
RETURN(Num1 + Num2)
ENDFUNCTION Meaningful identifiers
What will the following statement output? Variables, constants, subroutines and arrays all have identifiers (names). If you
call a variable X, then there is no indication of what it is storing or what its
OUTPUT(Calculate(1,2))
purpose is. If instead, it is called Total, then you know that it is storing a
31 Write a program statement to call the following function with the total.
parameter 100 and output the return value.
The identifiers for subroutines are usually descriptions of their function. For
FUNCTION FindValue(Number)
example, a procedure to output the numbers 1 to 10 could be called
Number ← Number + INPUT Function1, but then there is no indication of what it does. Instead, it could
RETURN Number be called Output1To10.
ENDFUNCTION
32 Write a procedure to take three numbers as parameters and output the Comments
largest. A comment is a description of a line of code, or section of code. To write a
33 Write a function that takes two strings as parameters. It takes the first 3 comment you use a special character or characters, for example, //. This tells
characters of each string and combines them, returning the resulting the program not to
string. execute the text after this symbol.
You do not need to comment every line of code, for example, the statement
Count = 0 does not need commenting, it is clear that it is storing 0 in the
8.13 Library routines variable count.
A program library is a set of subroutines that are pre-written and that can be Example 1
called The function of the FOR loop is written as a comment:
within a program.
FOR Count ← 0 TO 9 //Output the first 10
In some programming languages the operators for MOD and DIV are library
functions. In other programming languages they are just operators. For
elements in the array
example, 2 MOD 4 is the same as MOD(2, 4). OUTPUT(Array[Count])
NEXT Count
Two other library routines that you need to know are ROUND and RANDOM.
VB.NET
ROUND For count = 0 To 9 'output the first 10
This will take a real number (decimal) and limit how many numbers there are elements in the array
after the decimal point. Console.WriteLine(arrayData(count))
For example ROUND(10.123, 1) will take the number 10.123 and only Next
leave 1 number after the decimal point, returning 10.1. Python
ROUND(4.8293, 2) will return 4.82. for count in range(0, 10): output the first 10
As with functions, the values it returns need to be used. This could be done by elements in the array
outputting the return value, or saving it in a variable, e.g. print(arrayData[count])
RoundedValue ← ROUND(77.293, 1) Java

VB.NET public static void main(String args[]){


Integer[] arrayData = new Integer[10];
Dim roundedValue As Single
//insert code to populate the array
roundedValue = Math.Round(77.293, 1)
Python //output the first 10 elements in the array
for(Integer count = 0; count < 11; count++){
roundedValue = round(77.293,1)
System.out.println(arrayData[count])
Java }
public static void main(String args[]){ }
double value = Math.round(77.23 * 10.0) / Example 2
10.0; OUTPUT("Enter a number")
} INPUT Num1
RANDOM OUTPUT("Enter a number")
INPUT Num2
This will generate a random number between two values that it takes as //find and output the largest number
parameters. For example, RANDOM(10, 20) will return a number between IF Num1 > Num2 THEN
10 and 20. OUTPUT(Num1)
ELSE
ACTIVITY 8.4 OUTPUT(Num2)
ENDIF
Is there such a thing as a random number? Research how computers
generate random numbers and work out if there is such a thing as a truly
random number. Find out why randomness is important in programming VB.NET
and what the potential consequences are of having a system that does Dim num1 As Integer
not generate random numbers. Dim num2 As Integer
Console.WriteLine("Enter a number")
num1 = Console.ReadLine
RANDOM(1, 4) will return a number between 1 and 4.
Console.WriteLine("Enter a number")
As with functions, the values it returns and therefore need to be used. This num2 = Console.ReadLine
could be by outputting the return value, or saving it in a variable, e.g.
randomNumber = RANDOM(1, 100) 'find and output the largest number
VB.NET
If num1 > num2 Then
Console.WriteLine(num1)
Dim randomNumber As Integer Else
Dim rand As Random = New Random Console.WriteLine(num2)
randomNumber = rand.Next(1, 101) End If
Python Python
import random num1 = int(input("Enter a number"))
randomNumber = random.randint(1, 100) num2 = int(input("Enter a number"))
Java # find and output the largest number
public static void main(String args[]){ if num1 > num2:
Random rand = new Random(); print(str(num1))
Integer randomNumber = rand.nextInt(1000) + else:
1; print(str(num2))
}
Java Example 3
public static void main(String args[]){ Store the number 20 in the sixth position of the array named Numbers:
Scanner scanner = new Scanner(System.in); Numbers[5] ← 20
System.out.println("Enter a number");
Integer num1 = VB.NET
Integer.parseInt(scanner.nextLine()); Dim numbers(9) As String
System.out.println("Enter a number"); numbers(5) = 20
Integer num2 = Python
Integer.parseInt(scanner.nextLine());
if(num1 > num2){ numbers = [0,0,0,0,0,0,0,0,0,0]
System.out.println(num1); numbers[5] = 20
}else{ Java
System.out.println(num2) public static void main(String args[]){
} Integer[] numbers = new Integer[10];
} numbers[5] = 20;
Subroutines }
Subroutines help to split the code down into sections, especially when one Getting data out of an array
subroutine may need to be called multiple times. This means that if you need To access data in an array you need to know the identifier and the position of
to make any changes then you only need to make them once. For more on the data you want. This will be a value, so you need to do something with this
subroutines, look back at section 8.12. value, e.g. store it in a variable.
Example 1
ACTIVITY 8.5
Output the first value in the array Colours:
Open a computer program that you have written. Check its maintainability. OUTPUT(Colours[0])
Edit the program to improve the maintainability. Present your before and
after program and explain how you improved its maintainability. VB.NET
Console.WriteLine(Colours(0))
Questions Python
34 Explain how subroutines help make a program maintainable. colours = ['red']
35 Describe two other ways of making a program maintainable. print(colours[0])
36 Write a program statement to generate a random number between 1 and Java
5. public static void main(String args[]){
37 Identify the result from the statement ROUND(3.142, 1). String[] colours = new String[10];
System.out.println(colours[0]);
}
8.15 Arrays
Example 2
An array is a data structure. It allows you store multiple pieces of data in one
structure with one identifier. In an array, each data item must be of the same Store the second value in the array Colours in a variable:
data type. If it stores integers, then all values must be integers. If it stores
strings, then all values must be strings.
TheColour ← Colours[1]
VB.NET
1-dimensional arrays
theColour = colours(1)
A 1-dimensional array has just one row of data.
Python
The best way to visualise an array is with a table:
colours = ['red','yellow']
Index 0 1 2 3 4 theColour = colours[1]
Data 10 5 90 26 87 Java
This array has 5 spaces. Each space has an index. In this array the first data public static void main(String args[]){
item is in position 0, the data value is 10. In the second array space (index 1), String[] colours = new String[10];
the number 5 is stored. colours[0] = "red";
Arrays can be 0-indexed or 1-indexed. This depends on the programming colours[1] = "yellow";
language that you use. Some arrays start with 0 as the first space. Some String theColour = colours[1];
arrays start with 1 as the first space. }
Arrays use brackets after the identifier to indicate the index you want to
access. For example, Array[0] is accessing the first element in the array Example 3
named Array. MyData[3] is accessing the fourth element in the array
named MyData. Add 10 to the third value in the array Numbers:

Putting data into an array Value ← 10 + Numbers[2]


You need to know the array identifier and the position where you want to store VB.NET
the data. value = 10 + numbers(2)
Example 1 Python
Store the colour "red" in the first position of the array named Colour: numbers = [0,1,2,3,4]
Colour[0] ← "red" value = 10 + numbers[2]
VB.NET Java

Dim colour(0) As String public static void main(String args[]){


colour(0) = "red" Integer[] numbers = new Integer[5];
numbers[0] = 0;
Python numbers[1] = 1;
colour = ["",""] numbers[2] = 2;
colour[0] = "red" numbers[3] = 3;
Java numbers[4] = 4;
Integer value = 10 + numbers[2];
public static void main(String args[]){ }
String[] colour = new String[1];
colour[0] = "red"; Using variables as indices
} The index in the array might be a variable that stores a number.
Example 2 Example
Store the colour "yellow" in the second position of the array named Ask the user which array element to output from the array colours:
Colour: OUTPUT("Enter the array element you want to
Colour[1] ← "yellow" output")
INPUT ToOutput
VB.NET
OUTPUT(Colours[ToOutput])
Dim colour(1) As String
VB.NET
colour(1) = "yellow"
Dim colours(9) As String
Python
colours(0) = "red"
colour = ["",""] colours(1) = "yellow"
colour[1] = "yellow" colours(2) = "black"
Java colours(3) = "green"
public static void main(String args[]){ Console.WriteLine("Enter the array element you
String[] colour = new String[2]; want to output")
colour[1] = "yellow"; Console.WriteLine(colours(Console.ReadLine))
}
Python Java
colours = ['red','yellow','black','green'] public static void main(String args[]){
print(colours[int(input("Enter the array Integer[] numbers = new Integer[20];
element you want to output"))]) Scanner scanner = new Scanner(System.in);
Java for(Integer count = 0; count < 20; count++){
public static void main(String args[]){ System.out.println("Enter a number");
String[] colours = new String[10]; numbers[count] =
colours[0] = "red"; Integer.parseInt(scanner.nextLine());
colours[1] = "yellow"; }
colours[2] = "black"; }
colours[3] = "green"; Example 3
System.out.println("Enter the array element Searching the values in the array values that has 50 values, for the data
you want to output"); input by the user:
Scanner scanner = new Scanner(System.in);
Integer choice = ValueToFind ← INPUT("Enter the value to find")
Integer.parseInt(scanner.nextLine()); FOR Count ← 0 TO 49
System.out.println(colours[choice]); IF Values[Counter] = ValueToFind THEN
} OUTPUT("Found it")
ENDIF
NEXT Count
VB.NET
Using iteration to read and write
Dim values(49) As Integer
If you have a set of values in an array you can use iteration to loop through
each of the elements in turn. For example, you might want to output all of the
'insert code to populate array
values one at a time. You could add together all of the values in an array and Console.WriteLine("Enter the value to find")
output the total. You might want to take 10 values in from the user and store Dim valueToFind As Integer = Console.ReadLine
each one in the array. For count = 0 To 49
These are all best done using a count-controlled loop. This is because you Console.WriteLine("Enter a number")
usually know how many values you want to enter, or how many values there If values(count) = valueToFind Then
are in the array that you want to work through. Console.WriteLine("Found it")
End If
Example 1
Next
Output all 10 elements in the array Colours:
Python
FOR Count ← 0 TO 9
values=[]
OUTPUT(Colours[Count])
# insert code to populate array
NEXT Count
valueToFind = int(input("Enter the value to
VB.NET find"))
Dim colours(9) As String for count in range(0, 50):
colours(0) = "red" if values[counter] = valueToFind:
colours(1) = "yellow" print("Found it")
colours(2) = "black"
colours(3) = "green" Java
colours(4) = "blue" public static void main(String args[]){
colours(5) = "white" Integer[] values= new Integer[50];
colours(6) = "orange" //insert code to populate array
colours(7) = "purple"
colours(8) = "grey" Scanner scanner = new Scanner(System.in);
colours(9) = "maroon" Integer valueToFind =
For count = 0 To 9 Integer.parseInt(scanner.nextLine());
Console.WriteLine(colours(count)) for(Integer count = 0; count < 50; count++){
Next System.out.println("Enter a number");
if(values[count] == valueToFind){
Python
System.out.println("Found it");
colours = }
['red','yellow','black','green','blue','white', }
'orange','purple', }
'grey','maroon']
for count in range(0, 10): 2-dimensional arrays
print(colours[count]) A 2-dimensional array is best viewed as a table with rows and columns.
Java
Index 0 1 2 3 4
public static void main(String args[]){ 0 10 5 90 26 87
String[] colours = new String[10];
1 3 15 74 62 5
colours[0] = "red";
colours[1] = "yellow"; 2 7 10 85 4 24
colours[2] = "black"; In a 2-dimensional array there are two indices. For example, from the table:
colours[3] = "green";
colours[4] = "blue"; Position[0, 0] is 10.
colours[5] = "white"; Position[0, 2] is 7.
colours[6] = "orange"; Position[4, 2] is 24.
colours[7] = "purple";
colours[8] = "grey"; Putting data into an array
colours[9] = "maroon"; You need to know which position, i.e. both indices, the across and the down.
for(Integer count = 0; count < 10; count++){ Example 1
System.out.println(colours[count]);
Store "red" in the first position in the array Colours:
}
} Colour[0, 0] ← "red"
Example 2 VB.NET
Ask the user to input 20 numbers and store each in the array Numbers: colours(0,0) = "red"
FOR counter ← 0 TO 19 Python
OUTPUT("Enter a number") numbers = [[''] * 5 for i in range(10)]
INPUT Numbers[Counter] numbers[0][0] = "red"
NEXT counter Java

VB.NET public static void main(String args[]){


String[][] colours = new String[10][10];
Dim numbers(20) As Integer colours[0][0] = "red";
For count = 0 To 19 }
Console.WriteLine("Enter a number")
numbers(count) = Console.ReadLine()
Next
Python
numbers =
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
for count in range(0, 20):
numbers[count] = int(input("Enter a
number"))
Example 2 Example 2
Store 10 in the array Data, in element 4 across and 3 down: Ask the user which element to store in data:

Data[4, 3] ← 10 OUTPUT("Enter dimension 1")


INPUT Index1
VB.NET
OUTPUT("Enter dimension 2")
data(4,3) = 10 INPUT Index2
Python Data ← Array[Index1, Index2]
numbers = [[0] * 5 for i in range(5)] VB.NET
numbers[4][3] = 10 Dim arrayData(9, 9) As String
Java 'insert code to populate array
Dim first As Integer
public static void main(String args[]){
Console.WriteLine("Enter dimension 1")
Integer[][] data = new Integer[10][10];
first = Console.ReadLine
data[4][3] = 10;
Dim second As Integer
}
Console.WriteLine("Enter dimension 2")
second = Console.ReadLine
Getting data out of an array Dim data As Integer
You need to know both indices to access the data. data = arrayData(index1, index2)
Example 1
Output the data in the array ArrayData, element 5 across and 1 down: Python

OUTPUT(ArrayData[4, 1]) arrayData = [[''] * 10 for i in range(10)]


#insert code to populate array
VB.NET
Console.WriteLine(arrayData(4,1)) index1 = int(input("Enter dimension 1"))
Python index2 = int(input("Enter dimension 2"))
data = arrayData[index1][index2]
arrayData = [[0] * 5 for i in range(5)]
print(str(arrayData[4][1])) Java

Java public static void main(String args[]){


Scanner scanner = new Scanner(System.in);
public static void main(String args[]){ String[][] arrayData = new String[10][10];
Integer[][] arrayData = new Integer[5][5]; //insert code to populate array
//insert data to populate array Integer index1 =
System.out.println(arrayData[4][1]); Integer.parseInt(scanner.nextLine());
} Integer index2 =
Example 2 Integer.parseInt(scanner.nextLine());
Access the data in the array colours, in the first element across and the third String data = arrayData[index1][index2];
down: }
ColourAccessed ← Colours[0, 2] Using iteration to read and write
VB.NET Due to the two dimensions, you need two nested loops to read through all the
data elements. If you think about the table again, one loop goes through the
colourAccessed = colours(0,2) columns and one loop goes through the rows.
Python The first loop will check row 1. The column will change from 0, 1, 2, 3, 4. The
colours = [[''] * 5 for i in range(5)] row will stay the same at 0.
colourAccessed = colours[0][2] Index 0 1 2 3 4
Java 0 10 5 90 26 87
public static void main(String args[]){ 1 3 15 74 62 5
String[][] colours = new String[10][5]; 2 7 10 85 4 24
String colourAccessed = colours[0][2];
} The first loop will check row 2. The column will change from 0, 1, 2, 3, 4. The
row will stay the same at 1.
Using variables as indices
Each index can be stored in a variable in the same way as they can be in a 1D Index 0 1 2 3 4
array. 0 10 5 90 26 87
Example 1 1 3 15 74 62 5
Output the data in element 4,3: 2 7 10 85 4 24

First ← 4 It is best to use count controlled loops to go through the array.


Second ← 3 It has the structure:
OUTPUT(ArrayData[First, Second])
FOR row ← first index to last index
VB.NET FOR column ← first index to last index
Dim arrayData(9, 9) As String Code to run
'insert code to populate array NEXT row
Dim first As Integer = 4 NEXT count
Dim second As Integer = 3 Example 1
Console.WriteLine(arrayData(first, second))
DataArray has 10 elements by 3 elements. Output all of the elements in
Python the array:
arrayData = [[''] * 5 for i in range(5)] FOR Row ← 0 TO 2
first = 4 FOR Column ← 0 TO 9
second = 3 OUTPUT(DataArray[Column, Row])
print(arrayData[first][second]) NEXT Row
Java NEXT Count
public static void main(String args[]){ VB.NET
String[][] arrayData = new String[10][10]; Dim dataArray(2, 9) As Integer
//insert code to populate array 'insert code to populate array
Integer first = 4;
Integer second = 3; For row = 0 To 2
System.out.println(arrayData[first] For column = 0 To 9
[second]); Console.WriteLine(dataArray(row, column))
} Next
Next
Python
arrayData = [[''] * 2 for i in range(10)]
#insert code to populate array

for row in range(0, 3):


for column in range(0, 10):
print(arrayData[row][column]
Java
Python
public static void main(String args[]){
theArray = [[0] * 10 for i in range(15)]
Integer[][] dataArray = new Integer[3][10];
#insert code to populate array
//insert code to populate array
total = 0
for(Integer row = 0; row < 3; row++){
for row in range(0, 10):
for(Integer column = 0; column < 10;
for column in range(0, 15):
column++){
total = total + theArray[row][column]
System.out.println(dataArray[row]
print("Index",row,"has the total",total)
[column]);
} Java
} public static void main(String args[]){
} Integer[][] theArray = new Integer[10][15];
Example 2 //insert code to populate array
Search a 2-dimensional array, with 50 elements by 100 elements, for the value Integer total = 0;
input by the user:
for(Integer row = 0; row < 10; row++){
OUTPUT("Enter a number to search for") for(Integer column = 0; column < 15;
INPUT SearchValue column++){
FOR Row ← 0 TO 49 total = total + theArray[row][column];
FOR Column ← 0 TO 99 }
IF DataArray[Row, Column] = SearchValue System.out.println("Index " + row + " has
THEN the total " + total);
OUTPUT("Found it at " & Column & " " & }
Row) }
ENDIF
NEXT Column PROGRAMMING TASK 8.4
NEXT Row
The 2-player game of noughts and crosses has a grid of 3 squares by
VB.NET 3 squares (Figure 8.4).
Dim dataArray(50, 100) As Integer
'insert code to populate array
Dim searchValue as Integer
Console.WriteLine("Enter a number to
search for")
searchValue = Console.ReadLine()
for (row = 0 to 50) Figure 8.4: A noughts and crosses grid
for(column = 0 to 100)
if(dataArray(row, column) =searchValue) One player is noughts, the other is crosses.
then Each player takes it in turn to select a box to place their nought or cross.
Console.WriteLine("Found it at " & They cannot select a box that has already been chosen.
column & " " & row) The first player to get three of their symbols in a row (horizontally,
endif vertically or diagonally) wins. If the board is full and no-one has won then
next it is a draw.
next
Python Getting started

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.

Statement True False Invalid


if(10 < 20)
if(100 > < 2)
if(5 >= 5)
if(9 <= 8)
x ← 1
y ← 3
if(x = y)
num1 ← 100
num2 ← 200
if(num1 and
num2)
value1 ← 70
value2 ← 190
if(value1 <>
value2)

[7]

6 The 2-dimensional integer array, numbers , has 10 elements


by 20 elements.
Write an algorithm to initialise all of the elements to a random
integer value between 1 and 100. [4]
7 A program stores the x and y coordinates of a character in a
game.
The function move() takes an x coordinate as a parameter.
It asks the user to enter a movement (left or right) and
changes the coordinate:
• Right increases the coordinate by 1.
• Left decreases the coordinate by 1.
The function then returns the result.
a State why move() is a function and not a procedure. [1]
b The function move loops until the user enters either right
or left.
Write the function move() . [7]
[Total: 8]
8 Complete the table by stating how each of the features helps the
maintainability of a program.

Feature How it aids maintainability


Comments
Meaningful identifiers

[2]

9 A procedure twelve() reads an integer number from the


text file number.txt (e.g. 5). It then outputs the 12 times
table for that number (e.g. 5 × 1, 5 × 2 etc.).
Write the procedure twelve() . [6]

You might also like