Programming in Visual Basic 2024
Programming in Visual Basic 2024
Education
By
Prof. Dr. Ayman Haggag
Chapter 1 High Level and Low Level Languages
Chapter 1
High Level and Low Level Languages
Programming Languages
A computer program is a list of instructions that enable a computer to perform a specific
task. Computer programs can be written in high-level languages or low-level languages,
depending on the task to be performed. Most programmers write programs in high-level
languages.
High-Level Languages
High-Level Languages make use of words close
to human language. It is machine independent
and portable. It is problem and logic focussed.
High-level languages enable a programmer to
focus on the problem to be solved as they require no knowledge of the hardware of the
computer that will use the program.
High-level languages are closer to human language as it is closer to English. It is Portable
which means that it is independent of a particular type of computer. High level languages
include Python, Visual Basic, Java, etc.
Advantages of High-Level Languages
• Easier to understand for the programmer as it is closer to English.
• Faster to read, write and correct errors.
• Much easier to test and debug.
• No need to understand the workings of the computer.
• Works on many different machines and operating systems, i.e. portable.
• One line of code can carry out multiple commands.
Reasons to write programs in a High-Level Language:
• Closer to human language and English
o so it is easier and quicker to read, write, understand, and debug the program,
therefore, less likely to make errors.
• The program can be used on many different platforms
o because it is written in source code and is compiled into object code.
• Only need to learn a single language
o as this can be used on many different computers.
• They have built-in functions and libraries
o this saves time when writing the program.
• Do not need to manipulate memory addresses directly
o therefore, specialist knowledge of this is not required.
Low-Level Languages
Low-level languages relate to the specific architecture and hardware of a particular type of
computer. Low-level languages can refer to machine code, the binary instructions that a
computer understands, or an assembly language that uses mnemonic codes and needs to be
translated into machine code.
Translators
In order for programs to run on a computer, they need to be
translated into binary instructions, or machine code, that the
computer understands. This is done by a utility program called a
translator. There are several types of translator programs in use;
each one performs a different task.
A translator is needed as:
• The computer can only understand and run Machine code.
• Source code is required to be converted into binary
machine code.
Compiler
A compiler is a computer program that translates a program
written in a high-level language (HLL) into machine code all at once
so that it can be directly used by a computer to perform the
required task. Once a program is compiled, the machine code can
be used again and again to perform the same task without
recompilation. The compiler will:
• Translate the source code into object code.
• Translate the whole program as a complete unit all at once.
• Create an executable file or object code.
• Create a report of the list of all errors in the code.
• Optimise the machine code to run efficiently.
Interpreter
An interpreter is a computer program that reads a statement from a program written in a
high-level language, performs the action specified, and then does the same with the next
statement and so on. The Interpreter will:
• Translate a program one line of code at a time.
• The interpreter is used each time the program or source code is executed.
• Will identify an error as soon as it finds one in a line of code.
Features of an Interpreter
The interpreter is a translator that translates high level language into machine code. It
executes one line at a time. It translates source code line by line. It runs error diagnostic. It
produces error messages to tell user location of error. It stops execution when encounters
errors and continues translating when the error is fixed.
Advantages of using an Interpreter
• Easier to debug the code since an error is displayed as soon as it is found.
Comparison between Compiler and Interpreter
• A Compiler translates a whole program in one go while an Interpreter translates and
executes one line at a time.
• A Compiler produces a standalone object code while an interpreter doesn’t produce
standalone object code.
• Compilation process is slow but the resultant code runs very quickly while
interpreted code runs slowly.
• Interpreter stops when meets an error and then allows you to continue running from
where you stopped and correct errors in real-time while Compiler provides list of all
errors
• A Compiler produces list of all errors while an interpreter produces an error message
each time an error is encountered.
A programmer would make use of both an interpreter and a compiler
• Both translate high level language to machine code.
• The interpreter is used whilst writing the program.
• The interpreter is used to debug code line by line.
• The compiler is used when the program is completed to produce executable for
distribution.
• The compiler used to create separate executable file so compiler no longer needed.
• If it runs first time in a compiler there are no syntax errors.
Assembler
An assembler is a computer program that translates a program written in an assembly
language into machine code all at one so that it can be directly used by a computer to
perform the required task. Once a program is assembled, the machine code can be used
again and again to perform the same task without re-assembly.
Exmaple
Program Errors
As programs are written by humans, they may contain errors. There two types of error,
syntax errors and logical errors.
Syntax Error
Syntax is the structure of language statements in a computer program. A Syntax Error is
where a program statement doesn’t obey the rules of the programming language. A program
cannot be translated if it contains syntax errors.
Logic Error
A Logic Error is where the program doesn’t do what the programmer wanted it to do. Logic
errors are found when a program is being run.
When a program is being run, if it doesn’t do what it should do there is a logic error. These
can be found by tracing what the program does and using test data with expected results.
Chapter 2
Pseudocode and Flowcharts
Variable
A variable in a computer program is a named data store that contains a value, and that may
change during the execution of the program. In order to make programs understandable to
others, variables should be given meaningful names. Variable names should not have spaces.
Constant
A constant in a computer program is a named data store that contains a value, and that does
not change during the execution of the program. In order to make programs understandable
to others, constants should be given meaningful names, for example, Pi = 3.142. Constant
names should not have spaces.
Assignment
Values are assigned to a variable using the ← operator. The value of the expression on the
right of the ← is assigned to the variable on the left. The expression on the right can be a
single value or several values combined with mathematical operators.
Operator Action
+ add
- subtract
* Multiply
/ Divide
^ Raise to the power
() group
Examples of Pseudocode Assignments:
• Cost ← 10 Cost has the value 10
• Price ← Cost * 2 Price has the value 20
• Tax ← Price * 0.12 Tax has the value 2.4
• SellingPrice ← Price + Tax SellingPrice has the value 22.4
• Gender ←"M" Gender has the value M
• Chosen ← False Chosen has the value False
Standard Actions
Totalling
Totalling is used to sum a list of numbers. Keeping a running total of the value of goods sold
in a supermarket.
Counter Counter + 1
Counting is also used to count down until a certain value is reached, for example the number
of items in stock in a supermarket:
Begin/End
Terminator symbols are used at the beginning and end of each flowchart.
Process
Process symbols are used to show when values are assigned to
variables like an assignment in pseudocode. Used to show calculations.
Input/Output
Input/Output symbols are used show input of data and output of
information.
Decision
Decision symbols are used to decide which action is to be taken
next. These can be used for selection and repetition/iteration. Also used to show conditions.
Flow Lines
Flow lines are used to show the direction of flow which is usually, but not always, top to
bottom and left to right.
Continuation
To extend the flowchart to another page and allow it to join up.
A Trace Table can be used record the value of an item (variable) each time that it changes.
This manual exercise is called a Dry Run. A trace table is set up with a column for each
variable and a column for any output.
Example 3
Write an algorithm using pseudocode to find the biggest number out of two numbers.
INPUT First
INPUT Second
IF First > Second THEN
PRINT First
ELSE
PRINT Second
ENDIF
Dry run this algorithm using the following test data: 30, 15
PRINT Second
ELSE
PRINT Third
ENDIF
ENDIF
Visual Basic
Dim First As Integer
Dim Second As Integer
Dim Third As Integer
Console.Write("Enter the first numeber: ")
First = Console.ReadLine()
Console.Write("Enter the second numeber: ")
Second = Console.ReadLine()
Console.Write("Enter the third numeber: ")
Third = Console.ReadLine()
If First > Second And First > Third Then
Console.WriteLine(First)
Else
If Second > Third Then
Console.WriteLine(Second)
Else
Console.WriteLine(Third)
End If
End If
Console.ReadLine()
Example 5 (17 June P22 Q2)
Write an algorithm using pseudocode to input three different numbers, and then output the
largest number.
INPUT Num1
Biggest ← Num1
INPUT Num2
IF Num2 > Biggest THEN
Biggest ← Num2
ENDIF
INPUT Num3
IF Num3 > Biggest THEN
Biggest ← Num3
ENDIF
PRINT Biggest
Dry run this algorithm using the following test data: 10, 20, 13
Example 6
Write an algorithm using pseudocode to find the biggest number out of 4 positive numbers.
Highest ← 0
INPUT Number
IF Number > Highest THEN
Highest ← Number
ENDIF
INPUT Number
IF Number > Highest THEN
Highest ← Number
ENDIF
INPUT Number
IF Number > Highest THEN
Highest ← Number
ENDIF
INPUT Number
IF Number > Highest THEN
Highest ← Number
ENDIF
PRINT Highest
Dry run this algorithm using the following test data: 10, 20, 25, 13
Highest ← 0
FOR Counter ← 1 TO 10
INPUT Number
IF Number > Highest THEN
Highest ← Number
ENDIF
NEXT Counter
PRINT Highest
Dry run this algorithm using the following test data: 9, 7, 3, 12, 6, 4, 15, 2, 8, 5
6 4
7 15
8 15 2
9 8
10 5
15
Example 8
Write an algorithm to find the biggest and smallest numbers out of 10 positive number using
a FOR TO NEXT loop, assuming that the numbers range between 0 and 100.
Highest ← 0
Lowest ← 100
FOR Counter ← 1 TO 10
INPUT Number
IF Number > Highest THEN
Highest ← Number
ENDIF
IF Number < Lowest THEN
Lowest ← Number
ENDIF
NEXT Counter
PRINT Highest, Lowest
Dry run this algorithm using the test data: 9, 7, 3, 12, 6, 4, 15, 2, 8, 5
4 170
5 300
6 110
7 800
8 800 150
9 130
10 900
900 900 100
There is an error as the smallest number has not been identified. The algorithm only works
for numbers between 0 and 100; a better algorithm could look like this.
A modified algorithm to avoid the problem of the initial values
INPUT Number
Highest Number
Lowest Number
FOR Counter = 1 TO 9
INPUT Number
IF Number > Highest THEN
Highest ← Number
ENDIF
IF Number < Lowest THEN
Lowest ← Number
ENDIF
NEXT Counter
PRINT Highest, Lowest
Sub Main()
Dim Highest As Integer
Dim Lowest As Integer
Dim Number As Integer
Dim Counter As Integer
Console.Write("Enter a number: ")
Number = Console.ReadLine
Highest = Number
Lowest = Number
For Counter = 1 To 9
Console.Write("Enter a number: ")
Number = Console.ReadLine
If Number > Highest Then
Highest = Number
End If
If Number < Lowest Then
Lowest = Number
End If
Next
Console.WriteLine("The highest is: " & Highest)
Console.WriteLine("The lowest is: " & Lowest)
Console.ReadLine()
End Sub
Have a look at the flowchart showing the algorithm to select the largest and smallest
numbers from a list of 10 numbers.
68 18 86
86 27 65
86 27 50
86 27 40
86 27 30
86 27 -1 The highest temperature is,
86 Fahrenheit, 27 Celsius.
Chapter 3
Programming Concepts
Sequence
Sequence is the concept of one statement being executed after another.
Example 1
INPUT First
INPUT Second
PRINT First
PRINT Second
INPUT Mark
IF Mark >= 50 THEN
PRINT “Pass”
ELSE
PRINT “Fail”
ENDIF
INPUT Grade
CASE Grade OF
“A” : PRINT “Excellent”
“B” : PRINT “Good”
“C” : PRINT “Average”
OTHERWISE PRINT “Improvement is needed”
ENDCASE
IF … THEN … ELSE … ENDIF
For an IF condition the THEN path is followed if the condition is true and the ELSE path is
followed if the condition is false. There may or may not be an ELSE path. The end of the
statement is shown by ENDIF. A condition can be set up in different ways:
Using comparison operators
Comparisons are made from left to right, for example A > B means is A greater than B.
Comparisons can be simple or more complicated. For example:
REPEAT
OUTPUT "Enter three different numbers"
INPUT Number1, Number2, Number3
UNTIL Number1 <> Number2 AND Number2 <> Number3 AND Number3 <> Number1
INPUT Choice
INPUT Num1, Num2
CHASE Choice OF
1 : Answer Num1 + Num2
2 : Answer Num1 - Num2
3 : Answer Num1 * Num2
4 : Answer Num1 / Num2
OTHERWISE PRINT “Please enter a valid choice”
ENDCASE
Example
INPUT Choice
CASE Choice OF
1 : PRINT 'Option 1'
2 : PRINT 'Option 2'
3 : PRINT 'Option 3'
OTHERWISE PRINT 'Incorrect choice'
ENDCASE
IF Response = 1 THEN
X←X+Y
ELSE
IF Response = 2 THEN
X←X–Y
ELSE
IF Response = 3 THEN
X←X*Y
ELSE
IF Response = 4 THEN
X←X/Y
ELSE
OUTPUT "No response"
ENDIF
ENDIF
ENDIF
ENDIF
CASE Response OF
1:X←X+Y
2:X←X-Y
3:X←X*Y
4:X←X/Y
OTHERWISE OUTPUT ″No response″
ENDCASE
Loop Operation
FOR … TO … NEXT Fixed number of repetitions.
WHILE … DO … ENDWHILE Unknown number of repetitions.
The condition is tested at the beginning.
The loop may not be executed at all if the condition is false
from the first time.
REPEAT … UNTIL Unknown number of repetitions.
The condition is tested at the end.
The loop is always executed at least once.
Set Number of Repetitions (Counter Controlled Loop)
All types of loops can perform the task of set number of repetitions, for example repeating
10 times. However, the FOR … TO … NEXT loop is the most efficient for a set number of
repetitions. We call this a Counter Controlled Loop.
PosCount ← 0
NegCount ← 0
ZeroCount ← 0
FOR Count ← 1 TO 10
INPUT Number
IF Number > 0 THEN
PosCount ← PosCount + 1
ELSE
IF Number < 0 THEN
NegCount ← NegCount + 1
ELSE
ZeroCount ← ZeroCount + 1
ENDIF
NEXT Count
OUTPUT PosCount, " positive numbers"
OUTPUT NegCount, " positive numbers"
OUTPUT ZeroCount, " zeros"
Visual Basic
Dim PosCount As Integer
Dim NegCount As Integer
Dim ZeroCount As Integer
Dim Number As Integer
Dim Count As Integer
Console.WriteLine("Program created by: Name and Number")
For Count = 1 To 10
Console.Write("Enter a number: ")
Number = Console.ReadLine()
If Number > 0 Then
PosCount = PosCount + 1
Else
If Number < 0 Then
NegCount = NegCount + 1
Else
ZeroCount = ZeroCount + 1
End If
End If
Next
Console.WriteLine("Positive numbers: " & PosCount)
Console.WriteLine("Negative numbers: " & NegCount)
Console.WriteLine("Negative numbers: " & ZeroCount)
Console.ReadLine()
To make initial testing is more manageable
• Reduce the number of iterations to a manageable amount.
Example 15 Specimen P2 Q6 (b)
An algorithm, using pseudocode, which inputs 1000 numbers, outputs how many of these
numbers were whole numbers (integers). You may use the function INT(x) in, e.g. y = INT(3.8)
gives the value y = 3.
IntCount ← 0
FOR Counter ← 1 TO 1000
INPUT Number
IF INT(Number) = Number THEN
IntCount ← IntCount + 1
END IF
NEXT Counter
PRINT IntCount, “ whole numbers”
Total ← 0
FOR Counter 1 TO 10
REPEAT
INPUT Num
UNTIL Num > 0
Total ← Total + Num
NEXT Counter
PRINT Total
REPEAT
PRINT “Enter a positive number”
INPUT NumberOfNumbers
UNTIL NumberOfNumbers > 0
Total ← 0
FOR Counter ← 1 TO NumberOfNumbers
INPUT Number
Total ← Total + Number
NEXT Counter
Average ← Total/NumberOfNumbers
PRINT Total, Average
Visual Basic
Dim NumberOfNumbers As Integer
Dim Count As Integer
Dim Number As Integer
Dim Average As Double
Dim Total = 0
Console.WriteLine("Program created by: Name and Number")
Do
Console.Write("Enter a positive number: ")
NumberOfNumbers = Console.ReadLine()
Loop Until NumberOfNumbers > 0
For Count = 1 To NumberOfNumbers
Total 0
FOR Count 1 TO 50
INPUT Num
Total Total + Num
NEXT Count
OUTPUT Total
Describe the purpose of the algorithm.
The algorithm expects 50 numbers to be input, totals the numbers as they are entered by
carrying out a running total. It then outputs the result after all numbers have been entered.
Re-write the algorithm in pseudocode using a different type of loop.
WHILE … DO … ENDWHILE REPEAT ... UNTIL
Total ← 0 Total ← 0
Count ← 1 Count ← 1
WHILE Count <= 50 DO REPEAT
INPUT Num INPUT Num
Total ← Total + Num Total ← Total + Num
Count ← Count + 1 Count ← Count + 1
ENDWHILE UNTIL Count > 50
OUTPUT Total OUTPUT Total
To allow any number of inputs
• Use a variable for the counter upper limit that is input by the user.
• Alternatively, use a condition control loop until a condition is met.
INPUT Number
WHILE Number <> -1 DO
∞∞∞∞∞∞
∞∞∞∞∞∞
INPUT Number
ENDWHILE
If the user enters -1 in the first time, the loop may never be executed.
Example
Example of the use of a WHILE DO ENDWHILE loop to accept unknown number of inputs and
terminate when any negative number is entered.
INPUT Number
WHILE Number >=0 DO
∞∞∞∞∞∞
∞∞∞∞∞∞
INPUT Number
END WHILE
Example 4 (19 June P21 Q4)
PRINT "Input a value between 0 and 100 inclusive"
INPUT Value
WHILE Value < 0 OR Value > 100
PRINT "Invalid value, try again"
INPUT Value
ENDWHILE
PRINT "Accepted: ", Value
The entered number (Value) is being checked to see that it is not < 0 or not > 100. If it is, an
error message is displayed and the user has to enter another number, otherwise the number
is accepted, the word ‘Accepted’ is output along with the Value.
The trace table for this program code using the test data: 200, 300, -1, 50, 60
Example
Write an algorithm in pseudocode to accept an unknown number of marks, calculate a
running total, and output the total. The program ends when a mark of -1 is input.
Total 0
PRINT “Enter value for mark, -1 to end”
INPUT Mark
WHILE Mark <> -1
INPUT Number
WHILE Number <> 999 DO
IF Number >= 100 THEN
PRINT Number
ENDIF
INPUT Number
ENDWHILE
To change the algorithm to print out any numbers between 100 and 200 inclusive.
INPUT Number
WHILE Number <> 999 DO
IF Number >= 100 AND Number <= 200 THEN
PRINT Number
ENDIF
INPUT Number
ENDWHILE
Example
Example of the use of a WHILE DO ENDWHILE loop to accept any number of inputs and
terminate when a mark of -1 is entered. The program calculates the total of the marks
entered and then divides the total by the number of inputs to find the average. The
algorithm also checks if counter is zero when the user enters a -1 from the first time, it will
output “There is no Average.”
Total ← 0
Counter ← 0
INPUT Mark
WHILE Mark <> -1
Total ← Total + Mark
Counter ← Counter + 1
INPUT Mark
ENDWHILE
PRINT "The total is: ", Total
IF Counter = 0 THEN
PRINT “There is no Average.”
ELSE
Average ← Total/Counter
PRINT "The average is: ", Average
ENDIF
Total 0
REPEAT
INPUT Number
Total Total + Number
UNTIL Number = 0
PRINT “The total is “,Total
Example 2 (16 Nov P22 Q2)
This section of program code inputs positive numbers, discards any negative numbers and
then outputs the average. An input of zero ends the process.
Total 0
Counter 0
REPEAT
REPEAT
INPUT Num
UNTIL Num >= 0
REPEAT
PRINT “Enter a number between 0 and 100”
INPUT Number
UNTIL Number >= 0 AND Number <= 100
PRINT “The number is accepted”
INPUT Number
IF Number >= 0 AND Number <=100 THEN
OUTPUT ″The number is Acceptable ″
ELSE
OUTPUT ″The number is Rejected″
ENDIF
Using a Conditional Loop
The loop continues until a suitable input is supplied.
INPUT Number
IF Number > 100 THEN
OUTPUT ″The number is too large″
ELSE
Number RandInt(100)
TotalTry 0
REPEAT
PRINT "Enter your guess now, it must be a whole number"
INPUT Guess
IF Guess > Number THEN
PRINT "Too large try again"
ENDIF
IF Guess < Number THEN
PRINT "Too small try again"
ENDIF
TotalTry TotalTry + 1
UNTIL Guess = Number
PRINT "Number of guesses ", TotalTry
Visual Basic
Dim SecretNumber, NumberOfGuesses, Guess As Integer
Randomize()
SecretNumber = Int(Rnd() * 100) + 1
NumberOfGuesses = 0
Console.WriteLine("Program created by: Name and Number")
Do
Console.Write("Guess the secret number from 1 to 100: ")
Guess = Console.ReadLine()
NumberOfGuesses = NumberOfGuesses + 1
If Guess > SecretNumber Then
Console.WriteLine("Guess a smaller number")
End If
If Guess < SecretNumber Then
Console.WriteLine("Guess a larger number")
End If
Loop Until Guess = SecretNumber
Console.WriteLine("Correct Guess. The number of trials: " &
NumberOfGuesses)
Console.ReadLine()
Example 7 (20 Nov P21 Q3)
This pseudocode algorithm calculates the weight and number of bags in a load of firewood.
The weight in kilograms of each bag is input. The algorithm finishes when either 50 bags have
been weighed, or as soon as the total weight exceeds 1000 kilograms. Only then are the total
weight and the number of bags in the load output. The algorithm to calculate and display the
average weight of a bag of firewood in the load.
TotalWeight ← 0
BagCount ← 0
MaxBag ← 50
MaxWeight ← 1000
REPEAT
OUTPUT "Please Enter weight of bag"
INPUT Weight
TotalWeight ← TotalWeight + Weight
BagCount ← BagCount + 1
UNTIL TotalWeight > MaxWeight OR BagCount >= MaxBag
OUTPUT "Total weight of the load is ", TotalWeight
overweight bags weigh more than 1.1 kilograms. An input of a negative number stops the
process. Then the total number of bags, the number of overweight bags and the number of
underweight bags weighed are output.
Accept ← 0
Over ← 0
Under ← 0
OUTPUT "Enter weight of first cookie bag"
INPUT BagWeight
WHILE BagWeight > 0
IF BagWeight > 1.1 THEN
Error ← 1
ELSE
IF BagWeight < 0.9 THEN
Error ← 2
ELSE
Error ← 0
ENDIF
ENDIF
CASE Error OF
0 : Accept ← Accept + 1
1 : Over ← Over + 1
2 : Under ← Under + 1
ENDCASE
OUTPUT "Weight of next bag?"
INPUT BagWeight
ENDWHILE
Total ← Accept – Over – Under
OUTPUT "Number of bags weighed ", Total
OUTPUT "Number overweight ", Over
OUTPUT "Number underweight ", Under
The trace table for the given algorithm using this input data: 1.05, 0.99, 1.2, 0.85, 1.1, 0.9,
1.5, 0.95, 1.05, 1.00, 1.07, 0.89, –10
Chapter 4
Practical Programming
The traditional introduction to programming in any language is to display the words ‘Hello
World’ on a computer screen.
Constant
A CONSTANT in a computer program is a named data store that contains a value that does
not change during the execution of the program. In order to make programs understandable
to others, constants should be given meaningful names, for example:
Integer
An INTEGER is a positive or negative whole number that can be used with mathematical
operators.
Sequence
Statements are followed in sequence so the order of the statements in a program is
important. Assignment statements rely on the variables used in the expression on the right-
hand side of the statement all having been given values. Input statements often provide
values for assignment statements. Output statements often use the results from assignment
statements.
Selection
Selection is a very useful technique, allowing data items to be picked out according to given
criteria, for example selecting the largest value or the smallest value, selecting items over a
certain price, selecting everyone who is male. This is done with the use of if and case
statements.
The next instruction to be obeyed will depend upon what has already happened before and
a selection has to take place. Look at the following examples.
Validation
Case
Repetition
Sometimes instructions need to be repeated several times so a final result can be obtained,
this often involves the use of totalling and counting. Most programming languages support
three types of loop:
• a fixed number of repetitions.
• an unknown number of repetitions with at least one repetition, as the condition is
tested at the end of the loop.
• an unknown number of repetitions which may not be completed at all, as the
condition is tested at the beginning of the loop.
Totalling
Totalling is used with repetition with the total updated every time the loop is repeated.
Keeping a running total is one of the most frequently used programming techniques in many
computer systems, for example, the total on a receipt at a supermarket checkout.
Counting
Counting is used with repetition with the counter increased by 1 every time the loop is
repeated. Counting items or events is another of the most frequently used programming
techniques, for example, counting the number of items sold in a single transaction at a
supermarket.
As well as counting upwards, a counter can be used to count down with the counter being
decreased by 1 every time the loop is repeated, for example, removing an item from stock
every time one is sold.
Average
Program Output
Example
Tickets are sold for a concert at $20 each, if 10 tickets are bought then the discount is 10%, if
20 tickets are bought the discount is 20%. No more than 25 tickets can be bought in a single
transaction.
1. Write a program to calculate the cost of buying a given number of tickets.
2. Show how you would test your program.
Using Arrays
Chapter 5
Data Structures and Arrays
Introduction
One of the advantages of using computer systems is their ability to accurately repeat the
same tasks many times, for example, programs are written with loops for repetitions to work
with lists of similar items.
These lists are identified by the use of a single name and each item in the list can be found
by an index number showing the place in the list. This type of list is called a one-dimensional
array. The items in the list are the elements of the array. We use Arrays to simplify
programming and make programs shorter.
Array
An array is a series of elements of the same data type. It simplifies programs by reducing the
number of variables used.
Dimension
Number of indexes required to access an element in an array.
One-Dimensional Array
In order to use a one-dimensional array in a computer program, you need to consider:
• What the array is going to be used for, so it can be given a meaningful name.
• How many items are going to be stored, so the size of the array can be determined.
• What sort of data is to be stored, so that the array can be of the appropriate data
type.
We can declare the above array using pseudocode as follows:
DECLARE Colour [1:8]: String
Example
A one-dimensional array for all the students’ marks in a class is to be set up:
• Array name StudentMark. The name of the array cannot contain a space.
• Number of items in the array is the number of students in the class, for example 30.
• Whole numbers need to be stored, data type Integer.
We can declare the above array using pseudocode as follows:
DECLARE StudentMark [1:30]: Integer
Arrays usually start at element 1.
Sometimes the array starts at element 0, in this case the declaration will become:
DECLARE StudentMark [0:29]: Integer
FOR Counter 1 TO 30
INPUT StudentMark[Counter]
NEXT Counter
Example
FOR Count ← 1 TO 7
INPUT Number
Digit[Count] ← Number
NEXT Count
INPUT Number[Count]
NEXT Count
Extending the algorithm using pseudocode to also count and output how many of the
numbers stored in the array are greater than 500, using the variable Higher. Only output
Higher once with an appropriate message.
Higher ← 0
FOR Count ← 1 TO 5000
INPUT Number[Count]
IF Number[Count] > 500 THEN
Higher ← Higher + 1
ENDIF
NEXT Count
OUTPUT "There are ", Higher, " values that are greater than 500"
Output all Values from an Array
To output all marks from the array.
FOR Counter 1 TO 30
PRINT StudentMark[Counter]
NEXT Counter
Example
FOR Count ← 1 TO 7
OUTPUT Digit[Count]
NEXT Count
Example 15 June P22 Q5
Write an algorithm, using pseudocode and a FOR … TO … NEXT loop structure, to input 1000
numbers into an array.
FOR Count 1 TO 50
OUTPUT Name[Count]
NEXT Count
FOR I 1 TO 300
INPUT Name[I]
NEXT I
Loop with 300 repetitions starting at 1 and looping to 300. Values input are stored in
successive locations in an array called Name at position I. Next increases the loop counter I
by 1 and returns to the start of the loop.
Example 20 June P21 Q4
The pseudocode algorithm shown should allow numbers to be entered and should allow 50
numbers to be stored in an array.
Count ← 0
REPEAT
INPUT Values[Count]
Count ← Count + 1
UNTIL Count = 0
The value of the variable Count begins as 0 and is incremented by 1 before it is tested by the
loop condition. Count will never be 0 at the end of the loop.
To re-write the original pseudocode so that it terminates correctly and also prevents
numbers below 100 from being stored in the array Values[ ].
Count ← 0
REPEAT
INPUT Number
IF Number >= 100 THEN
Values[Count] ← Number
ENDIF
Count ← Count + 1
UNTIL Count = 50
To change your pseudocode so that it prevents numbers below 100 and above 200 from being
stored in the array Values[ ]. Alter the IF statement so that additional criteria set an upper
limit of <=200.
Example 17 Nov P21 Q2
This section of program code asks for 80 numbers between 100 and 1000 to be entered. It
checks that the numbers are in the correct range, and stores them in an array.
It also counts how many of the numbers are larger than 500 and then outputs the result
when the program is finished.
Count 0
FOR Index 1 TO 80
INPUT 'Enter a number between 100 and 1000', Number
Count ← 0
PosCount ← 0
NegCount ← 0
REPEAT
INPUT Number
IF Number > 0 THEN
PosCount ← PosCount + 1
PosNum[PosCount] ← Number
ENDIF
IF Number < 0 THEN
NegCount ← NegCount + 1
NegNum[NegCount] ← Number
ENDIF
Count ← Count + 1
UNTIL Count >= 50
OUTPUT "There are ", PosCount," positive numbers"
OUTPUT "There are ", NegCount," negative numbers"
Visual Basic
Dim PosCount, NegCount, Count, Number As Integer
Dim PosNum(50) As Integer
Dim NegNum(50) As Integer
Count = 0
Do
Number = Console.ReadLine()
If Number > 0 Then
PosCount = PosCount + 1
PosNum(PosCount) = Number
End If
If Number < 0 Then
NegCount = NegCount + 1
NegNum(NegCount) = Number
End If
Count = Count + 1
Loop Until Count >= 10
The algorithm needs to be changed so there is no limit to how many numbers can be input.
When the number 0 is input, the algorithm stops more numbers being input and outputs the
results. The number 9999 is not to be stored nor counted as a positive number.
PosCount ← 0
NegCount ← 0
INPUT Number
WHILE Number <> 0
IF Number > 0 THEN
PosCount ← PosCount + 1
PosNum[PosCount] ← Number
ENDIF
IF Number < 0 THEN
NegCount ← NegCount + 1
NegNum[NegCount] ← Number
ENDIF
INPUT Number
ENDWHILE
OUTPUT "There are ", PosCount," positive numbers"
OUTPUT "There are ", NegCount," negative numbers"
Example 19 Nov P21 Q4
The trace table for this algorithm using the input data: 58, 40, 67, 85, 12, 13, 75, 82.
Index 0
FOR Count 0 TO 7
INPUT Value
IF Value > 50 THEN
PassMarks[Index] Value
Index Index + 1
ENDIF
NEXT Count
PRINT "Number passed ", Index
The algorithm stores numbers greater than 50 in an array and finds and outputs the number
of times the pass mark has been met.
Example 18 June P23 Q3
This section of program code reads the contents of an array, totals the numbers and prints
out the sum and average of the numbers. Assume that the array is full.
Numbers [1:30]
Total 0
Counter 0
FOR Count 1 TO 30
Total Total + Numbers[Count]
Counter Counter + 1
Next Count
PRINT ′The sum of the numbers you entered is ′, Total
PRINT ′The average of the numbers you entered is ′, Total/Counter
Example 19 Nov P23 Q5
The algorithm performs an operation on the array named MyData. DIV means integer
division, so only the whole number part of the result is returned e.g. 7 DIV 2 returns a value
of 3.
First 0
Last 16
Found FALSE
INPUT UserIn
WHILE (First <= Last) AND (Found = FALSE) DO
This table shows the contents of the array: MyData e.g. MyData[2] stores the value 5
MyData
Index [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16]
Value 2 3 5 6 8 10 12 13 14 16 18 20 25 27 29 34 36
The algorithm searches for a value input by the user in the array.
Example 17 Nov P21 Q5
The flowchart below represents a program routine.
REPEAT
Flag 0
FOR Count 0 to 3
IF Num[Count] < Num[Count + 1] THEN
Store Num[Count]
Num[Count] Num[Count + 1]
Num[Count + 1] Store
Flag 1
ENDIF
NEXT Count
UNTIL Flag = 0
The trace table for the algorithm using the data given in the array.
The algorithm sorts numbers into descending order from largest to smallest.
.
Data Structure
We can use several Arrays with the same index to identify the same member across the
arrays.
This allows several arrays to be used together with the same index number to show related
information, for example, the student name would be stored in an array called StudentName
and his mark would be stored in another array called StudentMark.
FOR Counter 1 TO 30
INPUT StudentName[Counter]
INPUT StudentMark[Counter]
NEXT Counter
Output all Values from two Arrays
A FOR … TO … NEXT loop could be used to show values in the two arrays that store names
and marks of the students.
For Counter 1 to 30
PRINT StudentName[Counter]
PRINT StudentMark[Counter]
Next Counter
Highest Mark and the Student Name
We want to find the highest mark and the name of the student with the highest mark.
StudentName[1-30]
StudentMark[1-30]
HighestMark 0
BestStudent “Unknown”
FOR Counter 1 TO 30
IF StudentMark[Counter] > HighestMark THEN
HighestMark StudentMark[Counter]
BestStudent StudentName[Counter]
ENDIF
NEXT Counter
PRINT HighestMark
PRINT BestStudent
30
Chapter 6
Programming Projects
Project 1
Write and test a program to complete the three tasks.
TASK 1
Input and store the names and marks for 30 students who have sat three computer science
tests. Test 1 is out of 20 marks, Test 2 is out of 25 marks, Test 3 is out of 35 marks. You must
store the names in a one-dimensional array and the marks and total score for each student
in one-dimensional arrays. All the marks must be validated on entry and any invalid marks
rejected. You may assume that the students’ names are unique.
TASK 2
Calculate and store the total score for each student and calculate the average score for the
whole class. Output each student’s name followed by their total score, then output the
average score for the class.
TASK 3
Select the student with the highest score and output their name and score.
• Your program must include appropriate prompts for the entry of data.
• Error messages and other output need to be set out clearly and understandably.
• All variables, constants and other identifiers must have meaningful names.
Each task must be fully tested.
Index StudentNames StudentMarksTest1 StudentMarksTest2 StudentMarksTest3 StudentTotalScore
1
2
3
30
Sum
Average
Tasks 1, 2, and 3
Module Module1
Sub Main()
Dim StudentNames(30) As String
Dim StudentMarksTest1(30) As Integer
Dim StudentMarksTest2(30) As Integer
Dim StudentMarksTest3(30) As Integer
Dim StudentTotalScore(30) As Integer
Dim Mark1, Mark2, Mark3, Total, Sum As Integer
Dim ClassAverage As Double
Dim HighestScore As Integer
Dim BestName As String
Dim Count As Integer
Sum = 0
For Count = 1 To 30
Console.Write("Enter the name: ")
StudentNames(Count) = Console.ReadLine()
Do
Console.Write("Enter Mark 1 out of 20: ")
Mark1 = Console.ReadLine()
Loop Until Mark1 >= 0 And Mark1 <= 20
Do
Console.Write("Enter Mark 2 out of 25: ")
Mark2 = Console.ReadLine()
Loop Until Mark2 >= 0 And Mark2 <= 25
Do
Console.Write("Enter Mark 3 out of 35: ")
Mark3 = Console.ReadLine()
Loop Until Mark3 >= 0 And Mark3 <= 35
Total = Mark1 + Mark2 + Mark3
StudentMarksTest1(Count) = Mark1
StudentMarksTest2(Count) = Mark2
StudentMarksTest3(Count) = Mark3
StudentTotalScore(Count) = Total
Sum = Sum + Total
Console.WriteLine(StudentNames(Count) & " total is " &
StudentTotalScore(Count))
Next Count
ClassAverage = Sum / 30
Console.WriteLine("The average of the class is: " & ClassAverage)
HighestScore = 0
BestName = "Unknown"
For Count = 1 To 30
If StudentTotalScore(Count) > HighestScore Then
HighestScore = StudentTotalScore(Count)
BestName = StudentNames(Count)
End If
Next Count
Console.WriteLine(BestName & " got the highest score that is " & HighestScore)
Console.ReadLine()
End Sub
End Module
Sum 0
FOR Count 1 TO 30
INPUT Name
StudentName[Count] Name
INPUT Mark1, Mark2, Mark3
StudentMarksTest1[Count] Mark1
StudentMarksTest2[Count] Mark2
StudentMarksTest3[Count] Mark3
Total Mark1 + Mark2 + Mark3
StudentTotalScore[Count] Total
Sum Sum + Total
PRINT StudentName[Count], StudentTotalScore[Count]
NEXT Count
ClassAverage Sum/30
PRINT ClassAverage
Explain how you select the student with the highest score (Task 3). You may include
pseudocode or programming statements to help illustrate your explanation.
• Set a variable called HighestScore to zero and a variable called BestName to a dummy
value.
• Loop 30 times to check each student’s total score in turn against HighestScore.
• If student’s score > HighestScore then replace value in HighestScore by student’s
score and store student’s name in BestName.
• Output BestName and HighestScore outside the loop.
HighestScore 0
BestName “Unknown”
FOR Count 1 TO 30
IF StudentTotalScore[Count] > HighestScore THEN
HighestScore StudentTotalScore[Count]
BestName StudentName[Count]
ENDIF
NEXT Count
PRINT BestName, HighestScore
How does your program work when there is more than one student having the highest score?
Explain using your method given in the part above.
Project 2
Write and test a program to complete the three tasks.
TASK 1
A data logger records the temperature on the roof of a school twice a day, at midday and
midnight. Input and store the temperatures recorded for a month. You must store the
temperatures in two one-dimensional arrays, one for the midday temperatures and one for
the midnight temperatures. All the temperatures must be validated on entry and any invalid
temperatures rejected. You must decide your own validation rules. You may assume that
there are 30 days in a month.
TASK 2
Calculate the average temperature for midday and the average temperature for midnight.
Output these averages with a suitable message for each one.
TASK 3
Select the day with the highest midday temperature and the day with the lowest midnight
temperature. Then output each of these temperatures, the corresponding day and a suitable
message.
Module Module1
Sub Main()
Dim MiddayTemperature(30) As Double
Dim MidnightTemperature(30) As Double
Dim Count As Integer
Dim MiddayTotal As Double
Dim MidnightTotal As Double
Dim MiddayAverage As Double
Dim MidnightAverage As Double
Dim HighestMidday As Double
Dim LowestMidnight As Double
Dim HighestMiddayDay As Integer
Dim LowestMidnightDay As Integer
'Task 1
For Count = 1 To 30
Do
Console.Write("Enter the mid day temprature between -30 and 50 :")
MiddayTemperature(Count) = Console.ReadLine()
Loop Until MiddayTemperature(Count) >= -30 And MiddayTemperature(Count) <=
50
Do
Console.Write("Enter the mid night temprature between -30 and 50 :")
MidnightTemperature(Count) = Console.ReadLine()
Loop Until MidnightTemperature(Count) >= -30 And
MidnightTemperature(Count) <= 50
Next Count
'Task 2
MiddayTotal = 0
MidnightTotal = 0
For Count = 1 To 30
MiddayTotal = MiddayTotal + MiddayTemperature(Count)
MidnightTotal = MidnightTotal + MidnightTemperature(Count)
Next Count
MiddayAverage = MiddayTotal / 30
MidnightAverage = MidnightTotal / 30
Console.WriteLine("The average midday temperature is: " & MiddayAverage)
Console.WriteLine("The average midnight temperature is: " & MidnightAverage)
'Task 3
HighestMidday = -999
LowestMidnight = 999
For Count = 1 To 30
If MiddayTemperature(Count) > HighestMidday Then
HighestMidday = MiddayTemperature(Count)
HighestMiddayDay = Count
End If
Console.ReadLine()
End Sub
End Module
All variables, constants and other identifiers should have meaningful names.
In Task 1, you had to store the midday temperatures and midnight temperatures in arrays.
Write suitable declarations for these two arrays.
• DECLARE MiddayTemperature[1:30]: Real
• DECLARE MidnightTemperature[1:30]: Real
It has been decided to record the temperatures for one week rather than one month.
Write the new array declarations that you would use.
• DECLARE MiddayTemperature[1:7]: Real
• DECLARE MidnightTemperature[1:7]: Real
Declare two other variables that you have used and state what you used each one for.
• Variable 1: Counter: Integer
• Use: to use as a loop counter when entering the temperature.
• Variable 2: HighestMidday: Real
• Use: to store the highest midday temperature.
Write an algorithm to complete Task 2, using either pseudocode, programming statements
or a flowchart. Use temperatures for one week only. You should assume that Task 1 has
already been completed.
MiddayTotal ← 0
MidnightTotal ← 0
FOR Counter ← 1 TO 7
MiddayTotal ← MiddayTotal + MiddayTemperature[Counter]
MidnightTotal ← MidnightTotal + MidnightTemperature[Counter]
NEXT Counter
MiddayAverage ← MiddayTotal/7
MidnightAverage ← MidnightTotal/7
PRINT 'The average midday temperature is ', MiddayAverage
PRINT 'The average midnight temperature is ', MidnightAverage
Give a set of midday temperature data, for a week, that could be used to check your validation
rules for Task 1. Explain why you chose this data set.
HighestMidday ← -999
FOR Counter ← 1 TO 7
IF MiddayTemperature[Count] > HighestMiddayTemp THEN
HighestMiddayTemp ← MiddayTemperature[Counter]
HighestMiddayDay ← Counter
ENDIF
NEXT Counter
PRINT 'The highest midday temperature was ',HighestMiddayTemp,
' on day ', HighestMiddayDay
Project 3
In preparation for the examination candidates should attempt the following practical tasks
by writing and testing a program(s).
The manager of a parcel delivery service needs a program to check the size and weight of
parcels to determine which parcels can be accepted for delivery.
Write and test a program for the manager.
• Your program must include appropriate prompts for the entry of data.
• Error messages and other output need to be set out clearly.
• All variables, constants and other identifiers must have meaningful names.
You will need to complete these three tasks. Each task must be fully tested.
TASK 1 – Check the size and weight of a single parcel
Each parcel must obey the following rules to be accepted for delivery:
• each dimension must be no more than 80 cm
• the sum of the three dimensions must be no more than 200 cm
• the weight of the parcel must be between one and ten kilograms inclusive
Input and store the weight and dimensions for one parcel. All the dimensions and the weight
must be validated on entry and an unsuitable parcel rejected.
Output if the parcel is accepted or rejected. If rejected, output all the reasons why the parcel
was rejected.
TASK 2 – Check a customer’s consignment of parcels
Input and store the number of parcels in the consignment. Calculate the number of parcels
accepted and the total weight of the parcels accepted. For each parcel that was rejected,
output all the reasons why that parcel was rejected.
Output the number of parcels accepted and the total weight of parcels accepted.
Output the number of parcels rejected.
TASK 3 – Calculate the price for a customer’s consignment of parcels
Extend TASK 2 to also calculate the price for each parcel, using the following rules:
• 1 kg to 5 kg inclusive costs $10
• Each 100 grams over 5 kg, up to 10 kg, costs an extra $0.10
Your output should also include the price for each parcel accepted and the total price of the
consignment.
NumberAccepted = int (0)
NumberRejected = int (0)
TotalWeight = float (0)
Length = float (0)
Width = float (0)
All variables, constants and other identifiers should have meaningful names.
For each of the variables that you have used to record dimensions of the parcels in Task 1,
state the name, type and its use.
• Length, real/integer, length of parcel
• Breadth, real/integer, breadth of parcel
• Height, real/integer, Height of parcel
State two constants that you could have used for Task 1. Give the value that would be
assigned to each one.
• Dimension: 80
• TotalDimension: 200
• MaxWeight: 10.00
Write an algorithm to complete Task 1, using either pseudocode, programming statements
or a flowchart.
Give three different data sets that could be used to check your validation rules for Task 1.
Explain why you chose each data set.
• Data set: 30, 29, 28, 4
• Reason: normal data; parcel should be accepted
• Data set: 80, 60, 60, 10
• Reason: boundary data; parcel should be accepted
• Data set: 85, 60, 60, 11
• Reason: abnormal data; parcel should be rejected
Explain how your program calculates the price for a consignment (part of Task 3). You may
include programming statements as part of your explanation.
• loop for number of parcels
• parcels 5 kg or less use standard price
• over 5 kg use weight to calculate price