0% found this document useful (0 votes)
13 views88 pages

Programming in Visual Basic 2024

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13 views88 pages

Programming in Visual Basic 2024

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 88

Faculty of Technology and

Education

By
Prof. Dr. Ayman Haggag
Chapter 1 High Level and Low Level Languages

Chapter 1
High Level and Low Level Languages

Prof. Dr. Ayman Haggag 2 Faculty of Technology and Education (2023)


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.

Prof. Dr. Ayman Haggag 3 Faculty of Technology and Education (2023)


Chapter 1 High Level and Low Level Languages

Advantages of Low-Level Languages


• Can address memory locations directly.
• Shorter code which requires less storage or RAM.
• Can be written to run faster.
• Work directly on registers and the CPU.
• More control over what happens in the computer.
• Can use machine specific functions.
Assembly Language
Assembly language uses mnemonic codes. Assembly language is
often used to create drivers for hardware.
Reasons to write programs in a Low-Level Language:
Few programmers write programs in an assembly language. Those
programmers who do, do so for the following reasons:
• To write code that doesn’t take up much space in primary
memory.
• To write code that performs a task very quickly.
• To make use of special hardware.
• To make use of special machine-dependent instructions.
Machine Language (Machine Code)
Programmers do not usually write in machine code as it is
difficult to understand and it can be complicated to manage
data manipulation and storage. Programs written in machine
code do not need to be translated and can run directly on the computer.
Example

Prof. Dr. Ayman Haggag 4 Faculty of Technology and Education (2023)


Chapter 1 High Level and Low Level Languages

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.

Advantages of using a Compiler


• Once translated a stand-alone program file is created and there is no need for the
compiler when running the program.
• There is no need to distribute the source code which protects the rights of the creator
of the program.
Disadvantages of using a Compiler
• If the source code has errors, the program will not run at all.
• Future changes require the code to be recompiled which is not possible if the source
code is not available.

Prof. Dr. Ayman Haggag 5 Faculty of Technology and Education (2023)


Chapter 1 High Level and Low Level Languages

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.

Prof. Dr. Ayman Haggag 6 Faculty of Technology and Education (2023)


Chapter 1 High Level and Low Level Languages

Exmaple

Comparison between Complier, Interpreter and Assembler


Compiler Interpreter Assembler
Translates a high-level Executes a high-level Translates a low-level
language program into language program one language program into
machine code all at once. statement at a time. machine code all at once.
An executable file of No executable file of An executable file of
machine code is produced. machine code is produced. machine code is produced.
One high-level language One high-level language One low-level language
statement can be translated program statement may statement is usually
into several machine code require several machine translated into one machine
instructions. code instructions to be code instruction.
executed.
Compiled programs are Interpreted programs Assembled programs can be
used without the compiler. cannot be used without the used without the assembler.
interpreter.
A compiled program is An interpreter is often used An assembled program is
usually distributed for when a program is being usually distributed for
general use. developed. general use.
Example

Prof. Dr. Ayman Haggag 7 Faculty of Technology and Education (2023)


Chapter 1 High Level and Low Level Languages

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.

Errors when using a Compiler


When a program is being compiled, if any syntax errors are found no translated program is
produced. Instead, a list of all the errors in the whole program is produced. The programmer
corrects these errors and recompiles the program.
Errors when using an Interpreter
When a program is being interpreted, the interpreter performs the actions specified by each
statement until a syntax error is found. The programmer is then alerted to the place in the
program where the error was found. The error is corrected by the programmer and the
interpretation continues until the next error is found or the task is completed.

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.

Prof. Dr. Ayman Haggag 8 Faculty of Technology and Education (2023)


Chapter 1 High Level and Low Level Languages

Using an Integrated/Interactive Development Environment (IDE)


Most high-level programming languages offer
the use of an IDE for program development.
This contains an editor with an interpreter
and/or compiler together with debugging
tools, which can improve the speed of program
development.

Prof. Dr. Ayman Haggag 9 Faculty of Technology and Education (2023)


Chapter 2 Pseudocode and Flowcharts

Chapter 2
Pseudocode and Flowcharts

Prof. Dr. Ayman Haggag 10 Faculty of Technology and Education (2023)


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

Input Statements in Pseudocode


INPUT and READ are used for entry of data. INPUT or READ is usually followed by a variable
where the data input is stored, for example:

Prof. Dr. Ayman Haggag 11 Faculty of Technology and Education (2023)


Chapter 2 Pseudocode and Flowcharts

Output Statements in Pseudocode


PRINT and OUTPUT are used for the display of information. PRINT or OUPUT is usually
followed by a single value that is a string or a variable or a list of values separated by commas,
for example:

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.

Total  Total + Mark


Counting
Counting is used to find how many numbers or items there are in a list.Keeping a count of
the number of times an action is performed is another standard action.

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:

Prof. Dr. Ayman Haggag 12 Faculty of Technology and Education (2023)


Chapter 2 Pseudocode and Flowcharts

Standard Flowchart Symbols


Flowcharts are drawn using standard symbols.

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.

Prof. Dr. Ayman Haggag 13 Faculty of Technology and Education (2023)


Chapter 2 Pseudocode and Flowcharts

Using Trace Table


A thorough, structured approach is required to find out the purpose of an algorithm, which
involves recording and studying the results from each step in the algorithm. This will require
the use of test data and trace tables. A trace table shows the values of variables as you
manually test your program.

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

First Second Output


30 15
30

Dry run this program using the test data: 15, 30

First Second Output


15 30
30
Example 4
Write an algorithm, using pseudocode, which inputs three numbers and outputs the largest
of the three numbers.
INPUT First, Second, Third
IF First > Second AND First > Third THEN
PRINT First
ELSE
IF Second > Third THEN

Prof. Dr. Ayman Haggag 14 Faculty of Technology and Education (2023)


Chapter 2 Pseudocode and Flowcharts

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

Biggest Num1 Num2 Num3 Output


10
10 20
20 13
20 20

Example 6
Write an algorithm using pseudocode to find the biggest number out of 4 positive numbers.

Prof. Dr. Ayman Haggag 15 Faculty of Technology and Education (2023)


Chapter 2 Pseudocode and Flowcharts

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 Number Output


0 10
10 20
20 25
25 13
25 25
Example 7
Write an algorithm using pseudocode to find the biggest number out of 10 positive number
using a FOR TO NEXT loop.

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

Counter Highest Number Output


1 0 9
2 9 7
3 3
4 12
5 12 6

Prof. Dr. Ayman Haggag 16 Faculty of Technology and Education (2023)


Chapter 2 Pseudocode and Flowcharts

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

Counter Highest Lowest Number output


1 0 100 9
2 9 9 7
3 7 3
4 3 12
5 12 6
6 4
7 15
8 15 2
9 2 8
10 5
15 2

Identifying and Correcting Errors


Use a trace table and the test data 400, 800, 190, 170, 300, 110, 600, 150, 130, 900 to record
another dry run of the pseudocode.
The completed trace table should look like this:

Counter Highest Lowest Number output


1 0 100 400
2 400 600
3 600 190

Prof. Dr. Ayman Haggag 17 Faculty of Technology and Education (2023)


Chapter 2 Pseudocode and Flowcharts

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.

Prof. Dr. Ayman Haggag 18 Faculty of Technology and Education (2023)


Chapter 2 Pseudocode and Flowcharts

Prof. Dr. Ayman Haggag 19 Faculty of Technology and Education (2023)


Chapter 2 Pseudocode and Flowcharts

Example 17 June P21 Q6


This flowchart inputs a range of temperatures in degrees Fahrenheit.
As each temperature is input, it is compared with the previous highest temperature. If it is
higher than the current highest, it replaces the previous highest temperature and then it is
converted to degrees Celsius.
For ease of calculation, the final step of the Fahrenheit to Celsius conversion has been
approximated as division by 2.
When –1 is entered, the input process stops and the highest temperature (in both Fahrenheit
and Celsius) is output.

Complete the trace table for the input data:


68, 46, 50, 86, 65, 50, 40, 30, –1

HighF HighC TempF OUTPUT


-100 -100
68
68 18 46
68 18 50

Prof. Dr. Ayman Haggag 20 Faculty of Technology and Education (2023)


Chapter 2 Pseudocode and Flowcharts

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.

Example 18 June P23 Q5


The flowchart allows a set of 10 numbers to be entered; it finds and outputs the largest of
these numbers.

Prof. Dr. Ayman Haggag 21 Faculty of Technology and Education (2023)


Chapter 2 Pseudocode and Flowcharts

Complete the trace table for the input data:


6.30, 18.62, 50.01, 3.13, 2.05, 50.10, 40.35, 30.69, 0.85, 17.30

Prof. Dr. Ayman Haggag 22 Faculty of Technology and Education (2023)


Chapter 2 Pseudocode and Flowcharts

Max Counter Num OUTPUT


-1000.00 0 6.3
1 18.62
2 50.01
3 3.13
4
5
6
7
8
9
10

Prof. Dr. Ayman Haggag 23 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

Chapter 3
Programming Concepts

Prof. Dr. Ayman Haggag 24 Faculty of Technology and Education (2023)


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

Conditional Statements (Selection)


Selection decides which statements are to be executed depending upon the result of a
question. When different actions are performed by an algorithm according to the values of
the variables, conditional statements can be used to decide which action should be taken.
We use selection to allow different routes through a program dependent on meeting certain
criteria. There are two types of conditional statements as shown below with an example of
each.
1. IF … THEN … ELSE … ENDIF
2. CASE … OF … OTHERWISE … ENDCASE
When we have a condition that can be true or false: IF … THEN … ELSE … ENDIF, can be used,
for example:

INPUT Mark
IF Mark >= 50 THEN
PRINT “Pass”
ELSE
PRINT “Fail”
ENDIF

When we have to choose between several different values: CASE … OF … OTHERWISE …


ENDCASE, can be used, for example:

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:

Prof. Dr. Ayman Haggag 25 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

INPUT Height, Weight, Age


IF ((Height > 1) OR (Weight > 20) OR (Age > 5)) AND (Age < 70) THEN
PRINT “You can ride”
ELSE
PRINT “You can not ride”
ENDIF
Visual Basic
Dim Height, Weight As Double
Dim Age As Integer
Console.Write("Enter the height: ")
Height = Console.ReadLine()
Console.Write("Enter the weight: ")
Weight = Console.ReadLine()
Console.Write("Enter the age: ")
Age = Console.ReadLine()
If ((Height > 1) Or (Weight > 20) Or (Age > 5)) And (Age < 70) Then
Console.WriteLine("You can ride.")
Else
Console.WriteLine("You can't ride.")
End If
Console.ReadLine()
We use IF … THEN … ELSE … ENDIF
• When you have only 2 options.
• Conditions that use relational operators or checking for a range of values.
• Checking a condition that may be complex.
Comparison Operators
Operator Comparison
> Greater than
< Less than
= Equal
>= Greater than or Equal
<= Less than or Equal
<> Not Equal
() Group
AND Both
OR Either
NOT Not
Example 2
We can use IF in validation check for range check between 0 and 100:

OUTPUT "Enter a mark between 0 and 100 "


INPUT Mark
IF Mark >= 0 AND Mark <= 100 THEN
PRINT “Valid, In Range”
ELSE
PRINT “Invalid, Out of Range”
ENDIF

Prof. Dr. Ayman Haggag 26 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

Example 3 (17 June P21 Q5 (c))


Write an algorithm, using pseudocode, to input a number between 0 and 100 inclusive. The
algorithm should prompt for the input and output an error message if the number is outside
this range.

OUTPUT "Enter a number between 0 and 100 "


INPUT Number
IF Number < 0 OR Number > 100 THEN
OUTPUT "The number you have entered is outside the specified range."
ENDIF
Example 4
The algorithm below checks if a percentage mark is valid or not and if valid it will check for
Pass or a Fail. This makes use of two IF statements. The second IF statement is part of the
ELSE path of the first IF statement. This is called a nested IF.

PRINT "Enter a percentage mark between 0 and 100 "


INPUT PercentageMark
IF PercentageMark < 0 OR PercentageMark > 100 THEN
PRINT “Invalid Mark”
ELSE
IF PercentageMark >=50 THEN
PRINT “PASS”
ELSE
PRINT “Fail”
ENDIF
ENDIF
Visual Basic
Dim PercentageMark As Integer
Console.WriteLine("This program is created by: Name and Number")
Console.Write("Enter a percentage mark between 0 and 100: ")
PercentageMark = Console.ReadLine()
If PercentageMark < 0 Or PercentageMark > 100 Then
Console.WriteLine("Invalid Mark")
Else
If PercentageMark >= 50 Then
Console.WriteLine("PASS")
Else
Console.WriteLine("Fail")
End If
End If
Console.ReadLine()

Example 5 (18 Nov P22 Q2)


Write an algorithm, using pseudocode, to input three different numbers, multiply the two
larger numbers together and output the result. Use the variables: Number1, Number2 and
Number3 for your numbers and Answer for your result.

REPEAT
OUTPUT "Enter three different numbers"
INPUT Number1, Number2, Number3
UNTIL Number1 <> Number2 AND Number2 <> Number3 AND Number3 <> Number1

Prof. Dr. Ayman Haggag 27 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

IF Number3 < Number2 AND Number3 < Number1 THEN


Answer ← Number1 * Number2
ENDIF
IF Number2 < Number3 AND Number2 < Number1 THEN
Answer ← Number1 * Number3
ENDIF
IF Number1 < Number2 AND Number1 < Number3 THEN
Answer ← Number2 * Number3
ENDIF
OUTPUT "Answer = ", Answer
Visual Basic
Sub Main()
Dim Number1 As Integer
Dim Number2 As Integer
Dim Number3 As Integer
Dim Answer As Integer
Console.WriteLine("This program is created by: Name and Number")
Do
Console.WriteLine("Enter three different numbers")
Number1 = Console.ReadLine()
Number2 = Console.ReadLine()
Number3 = Console.ReadLine()
Loop Until Number1 <> Number2 And Number2 <> Number3 And Number3 <>
Number1
If Number3 < Number2 And Number3 < Number1 Then
Answer = Number1 * Number2
End If
If Number2 < Number3 And Number2 < Number1 Then
Answer = Number1 * Number3
End If
If Number1 < Number2 And Number1 < Number3 Then
Answer = Number2 * Number3
End If
Console.WriteLine("The answer is: " & Answer)
Console.ReadLine()
End Sub

• Test data set 1: 7, 7, 7 rejected as numbers are equal.


• Test data set 2: 1, 2, 3 normal data that should be accepted and answer should be 6.

CASE … OF … OTHERWISE … ENDCASE


For a CASE condition the value of a single variable decides the path to be taken. Several
values are usually specified. OTHERWISE is the path taken for all other values. The end of the
statement is shown by ENDCASE.
We us CASE … Of … OTHERWISE … ENDCASE
• Checking for discrete, large number of values, more than 2.
• To allow for multiple selections.
Example
The algorithm below specifies what happens if the value of Choice is 1, 2, 3 or 4.

INPUT Choice
INPUT Num1, Num2

Prof. Dr. Ayman Haggag 28 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

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

Example 18 June P22 Q3


This pseudocode algorithm inputs two non-zero numbers and a sign, and then performs the
calculation shown by the sign.

INPUT Number1, Number2, Sign


IF Sign = '+' THEN Answer ← Number1 + Number2 ENDIF
IF Sign = '-' THEN Answer ← Number1 - Number2 ENDIF
IF Sign = '*' THEN Answer ← Number1 * Number2 ENDIF
IF Sign = '/' THEN Answer ← Number1 / Number2 ENDIF
IF Sign <> '/' OR Sign <> '*' OR Sign <> '-' OR Sign <> '+' THEN Answer ← 0 ENDIF
IF Answer <> 0 THEN
PRINT Answer
ENDIF
We can improve the algorithm written in pseudocode by writing it using CASE.

INPUT Number1, Number2, Sign


CASE Sign OF
ꞌ+ꞌ : Answer ← Number1 + Number2
ꞌ-ꞌ : Answer ← Number1 - Number2
ꞌ*ꞌ : Answer ← Number1 * Number2
ꞌ/ꞌ : Answer ← Number1 / Number2
OTHERWISE Answer ← 0
ENDCASE
IF Answer <> 0 THEN
PRINT Answer
ENDIF
Visual Basic
Sub Main()
Dim Number1, Number2, Answer As Integer
Dim Sign As Char
Console.WriteLine("This program is created
by: Name and Number")

Prof. Dr. Ayman Haggag 29 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

Console.Write("Enter the first number: ")


Number1 = Console.ReadLine()
Console.Write("Enter the operation: ")
Sign = Console.ReadLine()
Console.Write("Enter the second number: ")
Number2 = Console.ReadLine()
Select Case Sign
Case "+" : Answer = Number1 + Number2
Case "-" : Answer = Number1 - Number2
Case "*" : Answer = Number1 * Number2
Case "/" : Answer = Number1 / Number2
Case Else : Answer = 0
End Select
Console.WriteLine("The answer is: " &
Answer)
Console.ReadLine()
End Sub

Example 19 Nov P23 Q4


The following pseudocode algorithm uses nested IF statements.

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

The same pseudocode algorithm but using a CASE statement.

CASE Response OF
1:X←X+Y
2:X←X-Y
3:X←X*Y
4:X←X/Y
OTHERWISE OUTPUT ″No response″
ENDCASE

Prof. Dr. Ayman Haggag 30 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

Loop Structures (Repetition)


When some actions need repeating, this is called iteration. Loop structures are used to
perform the iteration. There are three different types of loop structure:
1. FOR … TO … NEXT
2. WHILE … DO … ENDWHILE
3. REPEAT … UNTIL

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.

FOR …TO … NEXT WHILE … DO … ENDWHILE REPEAT … UNTIL


Counter ← 0 Counter ← 0
FOR Counter ← 1 TO 10 WHILE Counter < 10 DO REPEAT
PRINT “*” PRINT “*” PRINT “*”
NEXT Counter Counter ← Counter + 1 Counter ← Counter + 1
ENDWHILE UNTIL Counter = 10
Counter ← 1 Counter ← 1
FOR Counter ← 1 TO 10 WHILE Counter <= 10 DO REPEAT
PRINT Counter PRINT Counter PRINT Counter
NEXT Counter Counter ← Counter + 1 Counter ← Counter + 1
ENDWHILE UNTIL Counter > 10
Counter ← 0 Counter ← 0
FOR Counter ← 1 TO n WHILE Counter < n DO REPEAT
∞∞∞∞∞∞ ∞∞∞∞∞∞ ∞∞∞∞∞∞
NEXT Counter Counter ← Counter + 1 Counter ← Counter + 1
ENDWHILE UNTIL Counter = n
FOR … TO … NEXT
A variable is set up with a start value and an end value and then incremented in steps of one
until the end value is reached and the iteration finishes. The variable can be used within the
loop so long as its value is not changed.

Prof. Dr. Ayman Haggag 31 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

Example 18 June P21 Q2


An algorithm to input 10 numbers. Count how many numbers are positive and how many
numbers are zero. Then output the results.

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.

Prof. Dr. Ayman Haggag 32 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

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”

Example 16 June P22 Q2


Efficient program to input 10 positive numbers with validation and output the total.

Total ← 0
FOR Counter  1 TO 10
REPEAT
INPUT Num
UNTIL Num > 0
Total ← Total + Num
NEXT Counter
PRINT Total

Example 17 Nov P22 Q2


An algorithm using pseudocode to input a positive integer, use this value to set up how many
other numbers are to be input, input these numbers and calculate and output the total and
the average of these numbers.

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

Prof. Dr. Ayman Haggag 33 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

Console.Write("Enter a number: ")


Number = Console.ReadLine()
Total = Total + Number
Next
Average = Total / NumberOfNumbers
Console.WriteLine("The average is " & Average)
Console.ReadLine()

Example 18 Nov P21 Q4


An algorithm is written in pseudocode:

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.

Prof. Dr. Ayman Haggag 34 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

WHILE … DO … ENDWHILE with unknown number of repetitions


(Condition Controlled Loop)
This loop structure is used when the number of repetitions/iterations is not known and the
actions are only repeated WHILE a given condition is true. If the WHILE condition is untrue
when the loop is first entered, then the actions in the loop are never performed. In the WHILE
the condition comes at the beginning of the loop so we call it pre-test or pre-condition.
Example
Example of the use of a WHILE DO ENDWHILE loop to accept unknown number of inputs and
terminate when a number of -1 is entered.

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 name for this type of validation check is Range check.

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

Prof. Dr. Ayman Haggag 35 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

The flowchart to represent this section of program code.

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

Prof. Dr. Ayman Haggag 36 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

Total  Total + Mark


PRINT “Enter value for mark, -1 to end”
INPUT Mark
ENDWHILE
PRINT “The total is “, Total
Example 18 March P22 Q2
Write an algorithm in pseudocode to input some numbers and print out any numbers that
are greater than or equal to 100. The number 999 stops the algorithm.

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

Prof. Dr. Ayman Haggag 37 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

Dim Mark As Integer


Dim Total As Integer
Dim Count As Integer
Dim Average As Double
Total = 0
Count = 0
Console.WriteLine("Program created by: Name and
Number")
Console.Write("Enter a Mark, -1 end: ")
Mark = Console.ReadLine()
While Mark <> -1
Total = Total + Mark
Count = Count + 1
Console.Write("Enter a Mark, -1 end: ")
Mark = Console.ReadLine()
End While
Console.WriteLine("The total is: " & Total)
Console.WriteLine("The count is: " & Count)
If Count = 0 Then
Console.WriteLine("No average")
Else
Average = Total / Count
Console.WriteLine("The average is: " & Average)
End If
Console.ReadLine()

REPEAT … UNTIL with unknown number of repetitions (Condition


Controlled Loop)
This loop structure is used when the number of repetitions/iterations is not known and the
actions are repeated UNTIL a given condition becomes true. The actions in this loop are
always completed at least once. In the REPEAT UNTIL the condition comes at the end of the
loop so we call it post-test or post-condition.
Example 1
Write an algorithm to enter an unknown number of numbers terminated by a zero and carry
out the total.

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

Prof. Dr. Ayman Haggag 38 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

Total  Total + Num


Counter  Counter + 1
UNTIL Num = 0
Average  Total / (Counter - 1)
Print Average
Example 3
Example of a REPEAT UNTIL loop used to validate data entry and apply range check to only
accept a number between 0 and 100 inclusive.

REPEAT
PRINT “Enter a number between 0 and 100”
INPUT Number
UNTIL Number >= 0 AND Number <= 100
PRINT “The number is accepted”

Creating a Validation Check


We need a program is used to validate an input number and to check if this number is greater
than or equal to 0 and less than or equal to 100 and only accept valid input.

Using Conditional Statement


The problem with using IF THEN ELSE ENDIF structure is that it only allows one attempt at
inputting an acceptable value.

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.

WHILE DO ENDWHILE REPEAT … UNTIL


INPUT Number REPEAT
WHILE Number < 0 OR Number > 100 DO INPUT Number
OUTPUT ″The number is Rejected″ IF Number < 0 OR Number > 100 THEN
INPUT Number OUTPUT ″The number is Rejected″
ENDWHILE ENDIF
OUTPUT ″The number is accepted″ UNTIL Number >= 0 AND Number <= 100
OUTPUT ″The number is accepted″
Example 3 (18 June P23 Q4)
An algorithm is written in pseudocode:

INPUT Number
IF Number > 100 THEN
OUTPUT ″The number is too large″
ELSE

Prof. Dr. Ayman Haggag 39 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

OUTPUT ″The number is acceptable″


ENDIF
The purpose of the algorithm
The algorithm expects a number to be input, checks if the number is greater than 100 and
outputs the result of the test either ″The number is too large” or ″The number is acceptable″.
To re-write the algorithm in full, using pseudocode so that it continues until a suitable input is
supplied we will use a condition controlled loop.
WHILE DO ENDWHILE REPEAT … UNTIL
INPUT Number REPEAT
WHILE Number > 100 DO INPUT Number
OUTPUT ″The number is too large″ IF Number > 100 THEN
INPUT Number OUTPUT ″The number is too large″
ENDWHILE ENDIF
OUTPUT ″The number is acceptable″ UNTIL Number <= 100
OUTPUT ″The number is acceptable″
Example 20 Nov P22 Q3
This pseudocode algorithm is used as a validation check.

PRINT "Input a number from 1 to 5000"


REPEAT
INPUT Number
IF Number < 1 OR Number > 5000 THEN
PRINT "Invalid number, please try again"
ENDIF
UNTIL Number >= 1 AND Number <= 5000
PRINT Number, " is within the correct range"

Different types of test data


Extreme data
• 5000
• to check it is accepted
Normal data
• 300
• To check it is accepted
Abnormal data
• 10000
• To check it is rejected
Example 6 (19 Nov P22 Q2)
An algorithm is written in pseudocode to select a random number using the function
RandInt(n), which returns a whole number between 1 and the argument n. The algorithm
then allows the user to guess the number.

Number  RandInt(100)

Prof. Dr. Ayman Haggag 40 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

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

Prof. Dr. Ayman Haggag 41 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

OUTPUT "Number of bags in the load is ", BagCount


AverageWeight ← TotalWeight / BagCount
OUTPUT " Average weight of a bag of firewood is ", AverageWeight
Example 7 (18 June P22 Q2)
A flowchart for an algorithm to input numbers. Reject any numbers that are negative and
count how many numbers are positive. When the number zero is input, the process ends and
the count of positive numbers is output.

To also count negative numbers


Use another counter and update this counter when the number is less than zero. Output this
counter at the end.
Example 21 March P22 Q4
This algorithm accepts weights of bags of cookies. Any cookie bag weighing between 0.9 and
1.1 kilograms inclusive is acceptable. Underweight bags weigh less than 0.9 kilograms and

Prof. Dr. Ayman Haggag 42 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

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

Prof. Dr. Ayman Haggag 43 Faculty of Technology and Education (2023)


Chapter 3 Programming Concepts

There is an error in this algorithm.


• Error Total  Accept – Over – Under
• Correction Total  Accept + Over + Under

Prof. Dr. Ayman Haggag 44 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

Chapter 4
Practical Programming

Prof. Dr. Ayman Haggag 45 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

Programming in Visual Basic


Visual Basic is a general purpose high level
programming language that promotes rapid
program development and readable code.
First you run Visual Basic 2010 Express and then
choose New Project.
Then select Console Application.

The traditional introduction to programming in any language is to display the words ‘Hello
World’ on a computer screen.

Declaration and Use of Variables and Constants


Variable
A VARIABLE in a computer program is a named data store that contains a value that may
change during the execution of the program. In order to make programs understandable to
others, variables should be given meaningful names.

Prof. Dr. Ayman Haggag 46 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

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:

Const Pi As Double = 3.142 Sets up a Constant a real number = 3.142

Basic Data Types


In order for a computer system to process and store data effectively, different kinds of data
are formally given different types. This enables:
• data to be stored in an appropriate way, for example, as numbers or characters
• data to be manipulated effectively, for example numbers with mathematical
operators and characters with concatenation
• automatic validation in some cases.

Integer
An INTEGER is a positive or negative whole number that can be used with mathematical
operators.

Dim FirstInteger As Integer Sets up an integer variable.


Real
A REAL NUMBER is a positive or negative number with a fractional part. Real numbers can be
used with mathematical operators.

Dim FirstReal As Double Sets up a real variable.


Char
A variable or constant of type CHAR is a single character.

Dim Gender As Char Setup a Character variable.


String
A variable or constant of type STRING is several characters in length. Strings vary in length
and may even have no characters: an empty string. The characters can be letters and/or digits
and/or any other printable symbol. For example:

Dim TelephoneNumber As String Setup a String variable.


Dim FirstName As String Setup a String variable.
Boolean
A BOOLEAN variable can have only two values: TRUE or FALSE.

Dim AgeOver21 As Boolean Setup a Boolean variable.

Prof. Dr. Ayman Haggag 47 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

To make your program work


Programs work by automatically following one instruction after another in sequence.

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.

Prof. Dr. Ayman Haggag 48 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

Program written in Visual Basic IDE

The program while running

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.

Prof. Dr. Ayman Haggag 49 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

Program written in Visual Basic IDE

The program while running

Prof. Dr. Ayman Haggag 50 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

Validation

The program while running

Prof. Dr. Ayman Haggag 51 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

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.

Prof. Dr. Ayman Haggag 52 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

Fixed Number of Repetitions using For Loop

The program while running

Unknown Number of Repetitions using Repeat Until Loop

Prof. Dr. Ayman Haggag 53 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

The program while running

Unknown Number of Repetitions using While Loop

The program while running

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.

Prof. Dr. Ayman Haggag 54 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

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.

Prof. Dr. Ayman Haggag 55 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

Average

Program Output

Prof. Dr. Ayman Haggag 56 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

Maximum and Minimum

Program while running

Number Guessing Game


Rnd() is a random number generator that generates a random number between 0 and
0.99999. We multiply this by 100 to generate a number between 0 and 99.9999. Using the
function Int that truncates the fractional part we get an integer number between 0 and 99.
We add 1 to get a random integer number between 1 and 100.

Prof. Dr. Ayman Haggag 57 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

Program while running

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.

Prof. Dr. Ayman Haggag 58 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

The program written in Visual Basic IDE

The program while running

Prof. Dr. Ayman Haggag 59 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

Using Arrays

The program while running

Prof. Dr. Ayman Haggag 60 Faculty of Technology and Education (2023)


Chapter 4 Practical Programming

Two Parallel Arrays

The program while running

Prof. Dr. Ayman Haggag 61 Faculty of Technology and Education (2023)


Chapter 5 Data Structures and Arrays

Chapter 5
Data Structures and Arrays

Prof. Dr. Ayman Haggag 62 Faculty of Technology and Education (2023)


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

Prof. Dr. Ayman Haggag 63 Faculty of Technology and Education (2023)


Chapter 5 Data Structures and Arrays

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

Using a Variable as an Index in the Array


In order to repeat the same task many times for all the items in a list, each item needs to be
referred to in the same way using the index number for each element of the one dimensional
array. A variable is used for this index number.

Read or Write Values in an Array Using a FOR … TO … NEXT


Loop
A FOR … TO … NEXT loop uses a fixed number of repeats so it is ideal to use with an array,
when the number of elements is known, as the loop counter can be used as the array index.

Input all Values in an Array


FOR … TO … NEXT loop could be used to read all values into an array to store the marks of a
class of 30 students.

FOR Counter  1 TO 30
INPUT StudentMark[Counter]
NEXT Counter
Example
FOR Count ← 1 TO 7
INPUT Number
Digit[Count] ← Number
NEXT Count

The array for the input data: 5, 7, 0, 1, 2, 3, 4. Digit[] = [5, 7, 0, 1, 2, 3, 4]

Digit[1] Digit[2] Digit[3] Digit[4] Digit[5] Digit[6] Digit[7]


5 7 0 1 2 3 4
Example 20 Nov P22 4
This pseudocode algorithm allows 5000 numbers to be entered and stored in an array called
Number.

FOR Count  1 TO 5000

Prof. Dr. Ayman Haggag 64 Faculty of Technology and Education (2023)


Chapter 5 Data Structures and Arrays

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 1000


INPUT Numbers[Count]
NEXT Count
Rewrite your algorithm using another loop structure.
WHILE … DO … ENDWHILE REPEAT … UNTIL
Count  1 Count  1
WHILE Count <= 1000 DO REPEAT
INPUT Numbers[Count] INPUT Numbers[Count]
Count  Count + 1 Count  Count + 1
ENDWHILE UNTIL Count > 1000
Example 17 Nov P21 Q4 (b)
Write an algorithm in pseudocode, using a single loop, to print 50 names that have been
stored in an array.

FOR Count  1 TO 50
OUTPUT Name[Count]
NEXT Count

Prof. Dr. Ayman Haggag 65 Faculty of Technology and Education (2023)


Chapter 5 Data Structures and Arrays

Example 17 June P21 Q5


Describe the purpose of each statement in this algorithm.

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

Prof. Dr. Ayman Haggag 66 Faculty of Technology and Education (2023)


Chapter 5 Data Structures and Arrays

WHILE Number < 100 OR Number > 1000


INPUT 'This is incorrect, please try again', Number
ENDWHILE
Num[Index]  Number
IF Number > 500 THEN
Count  Count + 1
ENDIF
NEXT Index
PRINT Count
PRINT ' numbers were larger than 500'

Example 20 March P22 Q2


An algorithm has been written in pseudocode to input 50 numbers. Positive numbers are
stored in the array PosNum[ ]. Negative numbers are stored in the array NegNum[ ]. Zeros are
not included in the positive and negative counts.

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

Prof. Dr. Ayman Haggag 67 Faculty of Technology and Education (2023)


Chapter 5 Data Structures and Arrays

Console.WriteLine("There are " & PosCount &


" positive numbers")
For Count = 1 To PosCount
Console.WriteLine(PosNum(Count))
Next
Console.WriteLine("There are " & NegCount &
" negative numbers")
For Count = 1 To NegCount
Console.WriteLine(NegNum(Count))
Next
Console.ReadLine()

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

Prof. Dr. Ayman Haggag 68 Faculty of Technology and Education (2023)


Chapter 5 Data Structures and Arrays

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

Prof. Dr. Ayman Haggag 69 Faculty of Technology and Education (2023)


Chapter 5 Data Structures and Arrays

Middle  (First + Last) DIV 2


IF MyData[Middle] = UserIn
THEN
Found TRUE
ELSE
IF UserIn < MyData[Middle] THEN
Last  Middle - 1
ELSE
First  Middle + 1
ENDIF
ENDIF
ENDWHILE
OUTPUT Found

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 trace table for the input data: 10

First Last UserIn Middle Found OUTPUT


0 16 FALSE
0 16 10 8 FALSE
0 7 10 3 FALSE
4 7 10 5 TRUE TRUE

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.

Prof. Dr. Ayman Haggag 70 Faculty of Technology and Education (2023)


Chapter 5 Data Structures and Arrays

The array used in the flowchart contains the following data:

The trace table using the data given in the array.

Prof. Dr. Ayman Haggag 71 Faculty of Technology and Education (2023)


Chapter 5 Data Structures and Arrays

The purpose of the algorithm represented by the flowchart


Sorting the names in ascending Alphabetic order from A to Z from lowest to highest.
Example 20 Nov P22 Q5
This pseudocode represents an algorithm.

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 contents of the array at the start of the algorithm are:

The trace table for the algorithm using the data given in the array.

Prof. Dr. Ayman Haggag 72 Faculty of Technology and Education (2023)


Chapter 5 Data Structures and Arrays

The algorithm sorts numbers into descending order from largest to smallest.
.

Prof. Dr. Ayman Haggag 73 Faculty of Technology and Education (2023)


Chapter 5 Data Structures and Arrays

Data Structure
We can use several Arrays with the same index to identify the same member across the
arrays.

Index StudentName[Index] StudentMark[Index]


1 Ahmed 65
2 Tarek 50
3 Yasseen 70
… … …
… … …
30 Ziad 69

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.

Input all Values in two Arrays


A FOR … TO … NEXT loop could be used to enter values in the two arrays that store names
and marks of the students.

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

Prof. Dr. Ayman Haggag 74 Faculty of Technology and Education (2023)


Chapter 5 Data Structures and Arrays

Testing the algorithm


Counter StudentName (Counter) StudentMark (Counter) HighestMark BestStudent
0 Unknown
1 Ahmed 65 65 Ahmed
2 Tarek 50
3 Omar 70 70 Omar
4 Shams 80 80 Shams
5 Ziad 69

30

Prof. Dr. Ayman Haggag 75 Faculty of Technology and Education (2023)


Chapter 6 Programming Projects

Chapter 6
Programming Projects

Prof. Dr. Ayman Haggag 76 Faculty of Technology and Education (2023)


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

Prof. Dr. Ayman Haggag 77 Faculty of Technology and Education (2023)


Chapter 6 Programming Projects

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

Prof. Dr. Ayman Haggag 78 Faculty of Technology and Education (2023)


Chapter 6 Programming Projects

Declare the array to store the students’ names.

• DECLARE StudentNames[1:30]: String


Declare the arrays to store each student’s marks and total score.

• DECLARE StudentMarksTest1[1:30]: Integer


• DECLARE StudentMarksTest2[1:30]: Integer
• DECLARE StudentMarksTest3[1:30]: Integer
• DECLARE StudentTotalScore[1:30]: Integer
Show the design of your algorithm to complete Task 1 and Task 2 using pseudocode,
programming statements or a flowchart. Do not include any of the validation checks in your
algorithm.

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

Comment on the efficiency of your design.


• The algorithm is efficient because of using a single loop, this reduces the processing
time and the tasks are performed faster.
Show two different sets of student data that you could use to check the validation used in
Task 1. Explain why you chose each data set.

• Set 1: 20, 25, 35


• Reason for choice: valid data to check that data on the upper bound of each range
check is accepted.
• Set 2: 21, 26, 36
• Reason for choice: invalid data to check that data above the upper bound of each
range check is rejected.

Prof. Dr. Ayman Haggag 79 Faculty of Technology and Education (2023)


Chapter 6 Programming Projects

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.

• The first student with the highest score will be output.

Prof. Dr. Ayman Haggag 80 Faculty of Technology and Education (2023)


Chapter 6 Programming Projects

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.

Prof. Dr. Ayman Haggag 81 Faculty of Technology and Education (2023)


Chapter 6 Programming Projects

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

If MidnightTemperature(Count) < LowestMidnight Then


LowestMidnight = MidnightTemperature(Count)
LowestMidnightDay = Count
End If
Next Count
Console.WriteLine("The highest midday temperature was: " & HighestMidday & "
in day " & HighestMiddayDay)
Console.WriteLine("The lowest midnight temperature was: " & LowestMidnight & "
in day " & LowestMidnightDay)

Console.ReadLine()
End Sub
End Module

Prof. Dr. Ayman Haggag 82 Faculty of Technology and Education (2023)


Chapter 6 Programming Projects

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.

• Data set: 30, 29, 28, 31.5, 32.3, 33, 29.7


• Reason: normal data that should be accepted
• Data set: twenty, 23.99, seventeen, 501, –273, @#@, seventy seven
• Reason: abnormal data that should be rejected
Explain how you select the day with the highest midday temperature (part of Task 3). You
may include pseudocode or programming statements as part of your explanation.

• Set variable called HighestMidday to a large negative number.


• Loop 7 times to check each midday temperature in turn against HighestMidday.

Prof. Dr. Ayman Haggag 83 Faculty of Technology and Education (2023)


Chapter 6 Programming Projects

• If midday temperature > HighestMiddayTemp replace value in HighestMiddayTemp


by midday temperature and store the array index in HighestMiddayDay.
• Output HighestMiddayTemp outside the loop.
• Output HighestMiddayDay outside the loop.

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

Prof. Dr. Ayman Haggag 84 Faculty of Technology and Education (2023)


Chapter 6 Programming Projects

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)

Prof. Dr. Ayman Haggag 85 Faculty of Technology and Education (2023)


Chapter 6 Programming Projects

Height = float (0)


Weight = float (0)
Price = float (0)
TotalPrice = float (0)
SumOfDimentions = float (0)
More = int (0)
while More > -1:
Length = float (input("Enter the length of the parcel: "))
Width = float (input("Enter the width of the parcel: "))
Height = float (input("Enter the height of the parcel: "))
Weight = float (input("Enter the weigth of the parcel: "))
SumOfDimentions = Length + Width + Height
if (Length <=80) & (Width <=80) & (Height <=80) & (SumOfDimentions <=200) &(Weight >=
1) & (Weight <=10):
print ("Parcel Acceptabled")
NumberAccepted = NumberAccepted +1
TotalWeight = TotalWeight + Weight
if Weight <= 5:
Price = 10
else:
Price = 10 + (Weight - 5)
TotalPrice = TotalPrice + Price
print ("The price for this parcel is ", Price)
else:
NumberRejected = NumberRejected + 1
if Length > 80:
print ("Parcel Rejected as Length is greater than 80")
if Width > 80:
print ("Parcel Rejected as Width is greater than 80")
if Height > 80:
print ("Parcel Rejected as Height is greater than 80")
if SumOfDimentions > 200:
print ("Parcel Rejected as Sum Of Dimentions is greater than 200")
if Weight < 1:
print ("Parcel Rejected as Weight is less than 1")
if Weight > 10:
print ("Parcel Rejected as Weight is greater than 10")
More = int (input("Are there any more parecels, enter -1 when done "))
print ("Number of Parcels Accepted", NumberAccepted)
print ("Total wieght of Parcels Accepted", TotalWeight)
print ("Total price of Parcels Accepted", TotalPrice)
print ("Number of Parcels Rejected", NumberRejected)

All variables, constants and other identifiers should have meaningful names.

Prof. Dr. Ayman Haggag 86 Faculty of Technology and Education (2023)


Chapter 6 Programming Projects

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.

INPUT Length, Breadth, Height, Weight


IF Length <= 80 AND Breadth <= 80 AND Height <= 80 AND Weight >= 1 AND Weight <=10
AND Length + Breadth + Height <= 200 THEN
PRINT 'Parcel accepted'
ELSE
PRINT 'Parcel rejected'
IF Length > 80 OR Breadth > 80 OR Height > 80 THEN
PRINT 'At least one dimension too large'
ENDIF
IF Weight < 1 THEN
PRINT 'Parcel too light'
ENDIF
IF Weight > 10 THEN
PRINT 'Parcel too heavy'
ENDIF
ENDIF

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

Prof. Dr. Ayman Haggag 87 Faculty of Technology and Education (2023)


Chapter 6 Programming Projects

• Correct calculation of price


• keep running total of consignment price

Prof. Dr. Ayman Haggag 88 Faculty of Technology and Education (2023)

You might also like