Chapter 7 Programming
Chapter 7 Programming
PROGRAMMING
Chapter objectives
The learner must be able to:
. Describe features ofhigh level languages
. Apply features ofhigh level languages
. Use control structuresin designing programs
. Manipulate arrays
. Design input and output interfaces
. Design programs that read and write data to files
. Develop programs using functions and procedures
. Outline features of OOP
Introduction
Programming involves designing coding and testing of computer progrirms. This task is done by
specialists called programmers. This chapter looks at programming languages and concepts involved ia
developing, testing and deploying computer systems. Visual basic.Net shall be used in most examplel
especially the console mode.
Programming Languages
This refers to a set of symbols in computer language that are used in coding computer programr.
Common programming languages include |ava, Python, Visual Basic.Net, etc
. Is the language used to write programs in binary form (ls and 0s).
. Machine code executes without translation. !,
)
Advantages of Machine Language
. Programs run faster since they are already in computer language. There is no need for con-
version as programs are in machine language already.
. Programs occupy very small disc storage space by storing just ls and 0s.
Disadvantages of Machine tanguage:
. They are very difficult to learn.
. They are difficult to understand.
. Very difficult to use and therefore very few programmers use them these days.
. It takes too long to debug and therefore is prone to some errors.
. It takes too long to develop working programs.
They are machine dependent (they can only work on the type of computer they designed for
and not work on other computers)
b. Assembly Language!
. These are programming languages that use mnemonic codes in coding progrirms.
. Mnemonic codes are abbreviations used to represent instructions when coding assembly
language programs, for example, LDA for Load, ADD for Addition, etc.
. One assembly language statement is equivalent to one machine code instruction and therefore
programming is lenghy and time consuming.
. However, assembly language programs are efrcient.
. Programs also run faster as they are closer to machine language and therefore are used in
designing programs that needs eftcient timing, e.g. games like chess, operating systems, etc.
' Assembly language is used when there is need to access registers and memory addresses
directly.
. Assembly language instructions also occupy very little disc storage space.
. Mnemonic codes are very close to machine code, hence are low level assembly language
codes.
. They however run on specifc computer architecture since they are hardware aligned.
. They also contain different forms of instruction, e.g. jump, control, arithmetic, elc.
. Assembly language allows immediate, direct and other forms of memory addressing.
281
) High Level Languages (HLL):
These are programming languages that use English-like statements in coding programs, for
example COBOL, Pascal, BASIC, etc.
High Level languages are mostly used for developing user applications like stock control
systems, personnel records, etc.
There are so many high level languages because of competition from designers who want to
outpace each other.
It can also be due to the fact that we have so many application areas in real life so each high
level language is designed for a specific problem (problem oriented/problem speci6c) to bc
solved in our daily lives, for example BASIC was designed for learning PurPoses, COBOL for
business applications, FORTRAN for scientific purPoses, etc.
High Level languages are independent ofthe architecture of the computer.
One statement is translated into several equivalent machine code instructionS before it b
executed.
Below is an example of a BASIC program that accepts two numbers entered through thc
keyboard, adds them and display the result on the screen:
INPUT "Enter First Number.", A
INPUT "Enter Second Numberi', B
SUM=A+B
PRINTSUm
END
. Programs written in High Level Language are first converted to machine code before runni{,
. High level languages have the following features:
. Problem oriented (Machine independent): they are designed to solve an application problct
and therefore runs on any machine
. They are portable: they can be transferred from one machine to another and run withd
problem.
. Instructions are written in English statements which are easier to understand.
282 (
/
Disadvantages of HLL
. Takes long to run since they need to be first converted to machine code.
. They occupy a lot of disk storage space as compared to low level languages.
Types of High Level Languages/Programming paradigms
' Programming paradigm refers to methods used to categorise high level languages in terms of
organising principles used by the designers. It is a pattern that serves as a schoofif thought for
programming.
283
3. General purpose languages
These are languages that can be used to perform a variety of tasks; they are not dedicated to one
particular task.
4. Special purpose languages
. These are languages that are dedicated to a specific area, for instance, for running on embedded
computer systems like washing machines, mobile phones, controlling robots in a car assembly,
etc.
. such languages must support real-time facilities, and have the following facilities:
Advantages of OOP
Object oriented programming languages have the following advantages:
. Codes are usually short due code reuse
. More secure due to lnformation-hiding. Users only interact with an objectt methods, with tb
rest ofthe details hidden from the outside world.
. Debugging programs is very easy due to use of modules.
'. It is faster to write working programs because ofcode reuse
Programmers have small codes to maintain
Operators
Operators are used to manipulate data and they can be
a. Arithmetic operators: Like -, +, /, r, A, etc
b+c-d*e/f
e.g.
b. Logical operators s
And, or, Not tf
c. Assignmentoperators
/
i
d. Comparison/relationaloperators
>, <, <=, >=, <>, Is
Reserved words
Reserved words, also known as keywords, are words with a pre-defined meaning in
a specific
programming language, for example VB.Net has Dim, il End, integer etc. Reserved words
must not
be used as variables as they have an inbuilt function already spelt out to them within
the language.
Each programming language has its own reserved words, which may differ from other languages,
Within each programming language, there is a translator program that maintains a dictionary oiall
its reserved words. The translator will inform the user in the form of error messages if the keyword
is
wrongly used.
Variables
A variable is a name given to a memory location that stores a certain value, which may change (the
value) during program execution. Variables are 6eld identifiers, e.g. surnatne. Variables are
declared at
the beginning or at some point inside the program code. Every variable must be declared
before use,
otherwise an error is generated.
When using Visual Basic.Net, variables must be declared first before they are used. The keyword Dim
is used to declare variables, and each variable should have a data type, e.g.
Scope of variables
Scope ofa variable refers to the extent (within the program) that the variable is recognised (used)
in
relation to other modules and functions within the progr,rm. The scope of variables can be global or
local.
Global variables
These are variables that can be accessed and used by any procedure or function within the same
program. They are public variables. The value ofthe variable exists throughout the program and can be
accessed, modified or updated from any procedure within the program. Global variables are declared
outside the procedure or function. Any variable declared inside a procedure or function is not global
in scope. The key word Public can be used to declare global variables, for example:
Public Sname As String
The word Public implies that it is a global variable. However, one may just declare it using the DIM
statement. As long as it is outside a procedure, it is taken to be global in scope.
Local variables
Local variables are those variables that are declared within a procedure and that are accessible just
within the procedure they are declared. They are private variables, private to the procedure in which
they are declared or defined. The value ofthe variable only exists within the procedure it is defined.
Their values cannot be used or accessed by other procedures. Local variables are declared as follows:
Private Sname As String
Dim Age As Integer
. The above diagram shows that every variable name starts with a Letter, followed by any of the
following (Letter, digit or ) at any Position, or a mixture ofboth in any order, as long as the
-
first character is a letter.
. Using the diagram above, a variable like 3-Name, is invalid since it starts with a number.
. variable names must follow the rules of the language
. the translator tries the rules against the variable names used and reports.my errors
. The contents ofvariables must be ofa specific type otherwise an error created by the attemPted
use of anything else.
Constants
A constant is a variable whose value does not change during program execution. Its value is fixed-
Constants are used to rePresent data items with fixed values, e,g. the value ofpi. A constant is declared
as shown below:
Const pi=3.14159
If the constant is a string value, it must be enclosed in quotes, e.g.
Const Name = "Kapondeni"
Identifiers
An identifier is a unique label ofa data item or element ofa program and comprises ofone or more
characters. Identifiers include variable names, procedure names, constants, etc. Identifiers must not be
reserved words. Identifers can be user defined as long as they are not reserved words.
Rules for naming variables apply for all identifiers; that is for constants, procedure names, function
names, etc
Literals
A literal is a variable which is given a fixed value within the code of the program. It is the source
code representation of a fxed value. Literals are represented directly in a code-without requiring any
computation or the user to input the value during program execution, e.g.
Result and Name are given their values within the code and these are called literals.
Statements
A statement is a single instruction in a program which can be converted into machine code and
executed. A statement can just be one line of program code but in some cases a statement may have
more than one line. For example: -
Name = "Marian'
NumberA=a+b
The above are statements, which are basically assignment statements, that is, variable NumberA is
assigned the sum of the values ofvariables a and b. Thus, ifa = 2 and b = 3, NumberA is assigned the
value 5. The variable that is assigned a value must be on the left side ofthe assignment (=) sign.
An assignment statement is an instruction in a program that places a value into a variable, eg total =
a+b
In some cases, a statement may overlap into two or more lines. Lets look at the following single line
statement:
If a> b'Ihen MsgBox( % is bigger than bl, vbExclamation)
The following is another statement which spans over two lines.
287
Ifb<0]hen
MsgBox ("b is less than zero. Command cannot be executed", vbExclamation)
Flnd If
This is also a statement (starting at the IF and ending at End If.
Expressions
An expression is a construct made up of variables and operators that makes up a complete unit of
execution.
Example:
NumberA = a+b-c*d
The above is a statement. However, a+b'c*d is an expression found in a statement. Expressions can be
arithmetic (as given above), Boolean or string exPressions. For example,
(a>b) and (a>=c)
Operator precedence is very important in evaluating expressions and therefore it is imPortant to
enclose expressions is brackets where possible. Operator precedence is as follows, starting from the
highest to the lowest:
( ), Not, n, {-,i,}\,Mod, {+, -,}{=,<;,<=, 1= 1,...
NB: Operators in set braces indicates that they are in the same level.
Arithmetic expressions are evaluated first, followed by comparisons and lastly logical exPressions.
Block structure
A block is a group of statements between IF and End If structures. For example>
Procedures
A procedure is a self-contained module that does not return a vatue. It can also be defined as a sub-
program that performs a special task within the main program. A large program which is complicated
is uiually divided into smaller, self-contained sub-programs called modules and each module has e
special task to perform. For example, a program may have a procedure to calculate average, another
one to sort records and another one to display results and so on. Each procedure has a unique namc
within a program. The name ofthe procedure is an identifier for that procedure.
In VB.NJI, procedures start with the key word Private Sub, or Public Sub, followed by the procedure
name, and ends with the keyword End Sub, for example,
End Sub
\ Procedure Name / identifier
288 /
=-tl|-
Most procedures are defined by the programmer, that is, the user gives
a name he or she wants. If not
de6ned by the_user, the programming language will automatically-assign
its own rando- ,r"-..
The name of the procedure should be related to its task and should
u. r., ,i"l.ogr*-",- ,o
remember. Each procedure name_ must be unique within the same program. "".f
A procedure can be called from the main progiam or from any other
riodule. parameters are usually
passed when calling procedures or modules.
Functions
A function is a self-contained module that returns a value to the part of the program
which calls it
every time it is called or executed. A function can be an expression
that returns-a value when it is
called' A function performs a.single and special task, e.g. generate a student
number. Because they
return a value, firnctions are data types, e.g. integer, reai, etc. Thus the name
of a function is_ really
something like a variable since it stores a value. Functions can be in-built
or user-defined.
Task
Identifi vB.net inbuilt functions and explain their use. you may include a code snippet on how they
are applied in VB.
End Function
(Statements)
Note that a function ends with the statement End Function. The Public Function
above returns a
Boolean value (either TRUE or FALSE). the function name is just after the
word Function, i.e counr_
rec in the case above. On the other hand, the Private Function retruns
a date data type. Thus functions
returns a value ofa specific data type, which must be specified when the function
is decla.ed.
Syntax
Syntax ofa language refers to the grammatical rules governing sentence
construction in that language.
For example, Pascal uses a semi-colon (;) at the end ofeach instruction, it also
uses the rese.u.a (t"y)
word writeln to display items on the screen, etc. However, VB.Net does not have
semicolon at the
end ofeach instruction and it uses the keywo rd console.writeline
O to display values on the screen in
289
syntax errors
console applications. Each programming language has its own syntax A program with
does not run.
Semantics
The meaning attached to statements and the way they are used in a certain language.
A statement can
cannot be detected b7
be syntacticilly correct but semantically wrong. Semantic errors in a Program
the translator but by system users or other programmers'
Input operations
VB'Net allosr
Input operations are statements that prompt the user to enter data into the computer.
boxes, etc' Fc
tt ur., to enter data though form based interface, through console, through input
"
example:
lD = InputBox ("Enter Member Data to Search")
The above displays an input box with the message in bracket that prompts the user
to enter data thC
needs to be searched, as qiven below:
This type of interface is available both in console mode and in Windows form application
Output operations
Thesle are s-tatements that allow displaying or printing of results on the screen, e.g.
JrmPaYments'Show
It allows the Payment form to be displayed on the screen'
Programming Constructs I
rhei are the b-asis from which high level languages are built. Programming constructs includes:
a. Sequence control structures
b. SelectionStructures
290
/
I. If - Then - Else Constructs
II. Case statements
c. Looping Structures
I. For - Next construct
II. - Until construct
Repeat
III. While - Endwhile
29t
Dim A, B As Integer Dim A, B As lflteger
A = t ,'rt:tlt .Readline) A= ( ,tri't'lt ReadLine)
B -- t ,t tislit.ReadLine) B = t r'tt,,,l,. ReadLine)
IIA>BThen lfA>BIhen
t ; tt r t s t'i t.WriteLine(" A k bigger" ) t t'ti,.,tlr WriteLine("A is bigger")
End ! ElselJB>AIhen
If A < B'Ihen t'ott solt Writeline("8 is bigger")
( )ottsolt WriteLine(" B is bigger") Eke
End If ( ;attytlt Writeline("Nwnbers are cqual")
IfA = B Then End If
( )o tt s ob.WriteLine(' Numbers equal") { onsole.ReadKey)
End If
t.i,it-.r,/c
Nested If Statements
This is whereby the program has IF statements inside other IF statementi*Eliven in a program seg-
ment below:
I,f form = 4 Then
If Mark >= 50 And Mark <= 100 Then
result = "Passed"
<.uttsoIe .WriteLine("'Ihe student " & result)
EIse
result= "I:ailed"
()ousolt,.WriteLine("The s\udenl " & result)
End If
End tf
The statement Mark >= 50 And Mark <= 100 Then is found inside the statement l/prm = 4 Then,
f
therefore it will only be executed if the first IF is true. This is called nesting ofIF statements.
Question
Write a VB.Net program that accepts a student mark entered through a textbox and determines and
display the grade in a textbox using the following grading scale. Use the Select Case structure
75-100 A
60-74 B
50-59 C
45-49 D
34-44 E
0-33 U
Any other mark is invalid
292
The first task is to
GRADING PROGRAM
293
The Select case structure can use the following syntax ifvalues are not continuous
Case I,2, 6,79
Case Is 29
Case Is >40
Other variations are also acceptable.
Assignment
Code the same program above using the lF-Then-Elself-Endlf control structure. Include code for the
Clear button.
(c) Repetition/Iteration/Looping:
A contiol structute that repeatedly executes part of a program or the whole Program until a certain
condition is satisfied. Iteration is in the following forms: FOR...NEXT loop, REPEAT... UNTIL Loop
and the WHILE...ENDWHILE LooP.
For...Next Loop: A looping structure that repeatedly executes the loop body for a specified number
of times. The syntax of the For...Next loop is as follows:
A group of statements between the looping structures is called the loop body and is the one that is
repeatedly executed.
The For...Next loop is appropriate when the number ofrepetitions is known well in advance, e.g. fiw
times. An example of a program that uses tle For...Next loop is as follows:
294
/
'/
An IF statement may also include the statements, Continue for and Exit for
in them as given below:
A = t ,,tt:olt.ReadLine}
)fA<4Then
Exit For
F.nd tf
sum=sum+A
Continue For
Next i
(.ott:olL,WriteLine("Sun ttJ'nunbers is ', & sum)
( .ot tsole.ReadKey
Using VB.Net, the repeat ...until loop has many variations, which are as
follows:
Repeat
Statement I
Statement 2 Loopbody
Until {Condition}
I
Do
The following is a Visual Basic code of a program that accepts and calculates
the average of 5 num-
bers entered through the keyboard, using thi repeat until looping structure.
( ru t.Ltie.WriteLine ( )
( .ot solt-WriteLine (" lhe at,erage
r oJ numbers is " dz Average)
The following is a program that accepts numbers until the user enters the value 999 to stop further
loop execution:
t)tttsole.ReadKey)
NB. As for the Repeat...Until loop, the condition is tested after the loop body has been run at least
once, even when the condition is TRUE from start. This is rather misleading.
296
be executed at all if the condition set is FALSE from start. The s;,ntax of the WHILE...END WHILE
structure is as follows: .
WHILE {condition}
Statement I L
Statement z -nop
I
Uoay
END WHILE
An Exit While statement can be inserted at any point within the loop body in order to terminate the
loop when the need arises.
Nested loop
A nested loop is where a program can have a loop inside another loop. Nesting occurs when we have
a For Loop inside another For loop, or a While Loop inside a Repeat Until Loop, and so on.
297
Question
Write a program that implements a looping structure to produce the following pattern
nirt)+)+ t**
)+**r+,+
***rt*
**)+**
****
*)t)+
Task
Write nested loops that produce the following output (using For, Repeat, While loops)
(a)
29a
/
***
,f*
(b)*,+*)+
)+***
***+
It***
****
***+
(c) I
I 2
I ) 3
I ) 3
ll
121
i331
14641
1510 1051
161520 1561
Procedure Calls
nave a statement that calls another module (subprogram).
iril:#: "* consider the following
Dim frst, second As Inteper
Dim Sum As Inleger
Sub acceptNumbers( )
( ,ousok.WriteLine("Enter .,)
Jirst number
( )onsohReailLinej
frst =
( ) r t t s o lr.Writeline("
r
Enter Se c on d Number,, )
second = r' L, t t : ol r'.Readline}
End Sub
Sub Main}
Call acceptNumbers)
Call calcTotal}
Call DisplayTotao
t a r iolt.ReadKey0
r
End Sub
Sub calcTbtal}
Sum=frst+second
End Sub
Sub DisplayTotal)
299
t .,',::r,l' .WriteLine( lltt ,tt"t
'' & Sum)
End Sub
The above console mode program has 4 procedures or sub-Programs, each starting with
the keyword
Sub and ending with a phrase rnd sub. Each subprogram has its own function. The procedure names
are Main, acceptNumbers, calcTotal and DisplayTotal'
The variables drst, second and sum are not declared inside any ofthese procedures
and therefore are
global in scope.
6f ,h"r. 4 pirocedures, by default, Visual Basic runs the Sub Main 0 module first. Therefore the
a procedure' In
statement tlall acceptNumbers0 will be executed first. However, accePtNumbers is
that respect, the pro-cedure acceptNumbers will be invoked and run by the system.
After running this
procedure, the next statement to be run is Catl calcTotal 0 and so on'
can say Sub
in this case, the procedure Sub Main 0 has statements that call other procedures. Thus we
Main calls acceftNumbers through the statement Call acceptNumbers0
Sub Main)
accePtNumbers)
calcTotal0
DisPlaYTotal)
{.t,nsole .ReadKeY0
End Sub
is amodification
Also, the example does not use auser defined function as a sub-program The following
Main and cdcTotal 0
of the same program so that it accommodates a function within it. only Sub
needs to be modified as shown below
Function calcTotalU
,o1r7ogal = frst + second
End Function
Sub Main)
accePtNumbers0
Sum = calcTotal)
DkPlayTotaQ
Consolt'.ReadKey)
End Sub
calcTotalo has been converted into a function and not a procedure' Also, the statement
Sum = calcTotal0 has been included into the main module'
during
However, the calling statements in the above example do not send values to other Procedure
the procedure calls as they use global variables'
Parameter Passing
A parameter is an argument or value that is passed from one procedure to another' This allows
300 /
/
Procedures and functions to share vahtes to use in a given situation. The programmer needs
to specify
the actual values or variables whose values are to be-shared.
Parameters
_are
of two types, formar parameters and actuar parameters. Actuar parameters are
arguments found in the calling module/statement, which could be variables
or actual iaia like 30, 40.
Formal parameters are those variables that receive data from calling module
or statement.
Sub acceptNumbers)
Dim frst, sum, second As Integer
t )o ttsolL.WriteLine("Enter ,')
Jirst nuntber
frst = ( .e.Readline)
o t tso l
second = ( ;ott:olt.ReadLine}
't^irsl and Second are Actual paranteters
In the statement sum = calcTotal(firct, second), firstand second are the actual parameters,
whose values
are Passed on to a and b respectively. In this case a and b are the formal parameters.
It is also possible
to pass parameters by specifying the actual values other than variables, e-.g.
sum = calcTotal(34, 19)
30r
The variables will be as follows:
first second
T
50 is copied to memory
location B
[]
Note that these 4 are completely different memory locations in the computer. When passing by value,
45 is copied from first into memory location A, so A will be equal to 45. The value of second, 50, is
also copied to memory location B. However, if we change the value of A from 45 to 90, this does not
affect the value offirst since the memory spaces are different. Also, if we change the value ofB, this
does not affect the value of second. Thus in passing parameters by value, if the value of the formal
parameter is changed, it does not affect the value ofthe actual parameter since they point to diferent
memory locations.
P r i v at e S ub acceptNumb ers0
End Sub
Reference implies the address ofthe value in memory, the actual location ofthe value is the one that
is copied and passed to the formal parameter. In this regard, the actual and formal parameters will
be pointing to the same memory location even if the variables are diferent. It will be like 2 people
knowing the same person by diferent names, one calling him Kapondeni, while the other calling
him Tungamirai. Tungamirai and Kapondeni will be referring to one person, but being called using
different names by different people.
using the example above, memory location named first by module acceptnumbers is the same
memory location called A by function calcTotal.
I
302 t1
First (A) Second (B)
So
E E
if we change the value of A, it means that we have also changed the value of First
since the mem-
ory location is the same.
If the programmer does not specifr ByVal or ByRef function, Visual Basic assumes that
it is ByVal
by default.
Structured Programming
structured programming, is also known as modular, top-down prog!:rm design
or procedural
programming. It is whereby the
Programmer uses modules and subprograrns whei coding complex
Programs' It allows a top-down aPProach to program design. The progrinmer or developer creates a
program with subroutines, procedures and functions, each having its own
task. However, ihe program
have only one entry point and one exit point. Modern -programming languagls
$oulf
Basic.Net, Java, C++ allows modular approach to programrning.
like visual
303
Disadvantages of Modularisation
' Documentation will be long and thorough, therefore may take time to produce
Can lead to problems ofvariable names as the modules are developed separately by different
people.
. It may be difficult to link the modules together.
Source Code
This refers to the program written in High Level Language by the programmer, e.g. the visual basic
Code as tfn-ea the programmer. Source code is human understandable lang"ug" and cannot be
!f
understood by the comPuter. This therefore needs to be translated into machine-coie (binary) which
the computer can understand.
Object Code
This refers to a machine code version ofa source code. It a program in ls and 0s as understood by
the computer' All programs written in source code must be converted to object code for the comput-
er to understand them.
Translators
' These are programs used to convert High level Languag" progr"-,
",
*ritten by the pro-
grammer (source code) into machine code that the computer can execute.
. Translators are in three types, which are assemblers, interpreters and compilers, which are
further explained below:
l. Assemblers:
' These are Programs used to translate assembly language instructions (program) into machine
language instructions before execution.
.'
since each computer has its own assembly language, it also has its own assembler.
Assembler programs are written either using assembly language, or using high level languag-
es like C.
. Assemblers are simpler to program as compared to compilers.
. Assemblers are in two types: One-Pass Assemblers and Two-pass AsSemblers
/
* One-Pass Assemblers
' These go through the source code once and assume that all the symbols
will be defined
before any instruction could reference them. This is equivalent to declaring
variables at the
top ofthe source code regardless ofwhere they are used in a high rever lani.age
program.
' It has an advantage of speed since only one transration phase irigone throrigh'
* Two-Pass Assemblers.
' Creates a table with all the symbols and their values in the first pass and
then use the table in
the second pass to generate code.
'. Has an advantage that symbols can be defined at any stage in the source code.
Two-pass assemblers make programs easier to read and to maintain.
Use of Assemblers
.
The use of assemblers include:
*
They generate machine code that is equivalent to assembly language.
*
They are used to check the validity ofinstructions, that is, checkin! for syntax
errors in an
instruction.
* They also assign rnemory locations to variables.
2, Interpreters
' These are programs that translate and run one instruction (command) ofa program at a time
until the end of the program, e.g. the BASIC interpreter.
' The interPreter rnust be present in the computer to run the program. Itis
used during program
writing (coding) because it easily aids in debugging.
. An interpreter translates one instruction at a time and then executes it.
. The translated program retains the source code.
' They do not Produce the machine code version (object code) ofa program; hence
translation
is repeated every tirne the program is executed.
' Ifthe Program is run 100 times, translation for each instruction is also carried out 100 times.
Functions of Interpreters
. They translate each instruction in turn into machine language and run it.
. Allocates storage space to variables.
. They check syntax enors in a program statement.
. Gives error messages to the user
. Finds wrong and reserved words ofthe program
. Determines wrong use of variables
Advantages of interpreters
. It is easy to find and correct syntax errors in interpleted plograms.
'. There is no need for lengthy recompilation each time an error is discovered.
It is very fast to run programs for the first time.
I
' Allows development of small program segments that can be tested on their own without
writing the whole program.
. It is easier to partially test and debug programs, especially during the programming stage.
. It is very fast to run small programs.
305 /
. individual segments can be run, allowing errors to be isolated
. running will be necessary after very minor changes
Disadvantages of interpreters
. They are very slow in running very large programs.
. They do not produce an object code ofa source code and hence diffrcult to use since conver-
sion takes place eyery time the program is run.
3. Compilers
. These are programs that convert a high level language program into its machine code equiva-
lent at one go (at once) and then run it, e.g. the COBOL compiler.
. Compiler must be present for compiling the program only and NOT during the running
process.
. Creates an object code version of the source code
. Once compiled, the program no longer needs conversion since the machine code version is
the one that will be run, until some changes are made to the program code.
. Compilers run faster when called and therefore may be held as library routines.
. Once compiled, the program can then be run even on a computer without the compiler since
the program will already be in machine code.
. The compilation processes involves many complex stages.
Functions of Compilers
. They check syntax errors in program statements.
. They allocate storage space to variables.
. Translate the whole program into machine code at one go.
. Run object code ofthe program.
. Produces a program listing which indicates position of errors in a program.
. Gives error messages to the user
. Finds wrong and reserved words ofthe program
. Determines wrong use of variables
Advantages of Compilers
. The object code can be saved on the disc and run when needed without the need for compilation.
. Compiled programs run faster since only the object code is run.
. The object code can run on any computer, even those without the compiler. Therefore compiled
programs can be distributed to many users and used without any problems.
. The object code is more secure since it cannot be read without the need for reverse engineering.
. Cornpilers indicate the line numbers with syntax errors and therefore assist programmers in
debugging programs.
. They are appropriate even for very large programs.
Disadvantages of Compilers
. Slower than interpreters for running programs for the first time.
. They can cause the computer to crash,
. Difficult to find errors in compiled program.
. There is need for lengthy recompilation each time an error is discovered.
306 /
Difference between High Level Languages and Low Level
Languages
Slower in execution since they need to be Faster in execution since they are in machine
first converted to machine code before run-
Occupy large disk storage space on the com- Occupy small disk storage space on the com_
.'
Data types are declared at theteginning or at some point inside
the program code.
Data types for variables must be properly declared.
3. Currency
. Occupy 8 bytes with 0 as default value.
' used for handling monetary values and support up to 4 digits
to the left and 15 digits to the
left of the decimal point.
4. Date
. Represent date and time values and occupy g bytes.
5. Double
.'
stores-a double precision floating point number with decimal places
but longer than single.
Default is 0 and occupies g bytes
307 ll
5. Single
. Stores a single precision floating point number, with decimal places.
. Default is 0 and occupies 4 bytes.
7. Long
. Short for long integer and default value is 0.
. It occupies 4 bltes from -2 L47 483 648 to -2 I47 483 647.
Variable length:
Does not specifr the number of characters, each data items occupies the number ofspaces it re-
quires.
This is declared as follows
Dim Sname as string
2. Boolean
Represents instructions that evaluate to either True or False only. The default value is False
and occupy 2 bytes of storage.
Mostly used together with If..... Then....... Else Construct.
3. Character
A data type that holds just one alphabetic or special character like 70, $, a, etc.
Can be written as char in most programming languages.
308 I
Arrays
which stores and implements a set of data
*:::*f".",**:::::.:":" items of the same data
ffi Hil: :::i:1" :*:lT:::r:,1y *;;,
:'"r.d"1.:16:;;;;#fi::il:Hil""::;
;l:ff :lii"ffi:'i,::'^*::::i :::r::y:,. i,
It can either store numbers or strings, f,ut
g:1.':
;.?.r"*;ffi il:"Ul,t; ffi ::J?
n", U",f,
Below is an called Names; ""Ir"n.
The numbers o, r,2' 3 and 4.,are the indices (index positions). The array has positions 0, 1,2,
is Michei,a, at position r is rinaye aid 3 and+.
fj ffi1:.": ""re si L vi.i"i ilog;;;_,r,g, ,r,,, ."n
"r.
Names(0) = "Micheilla"
Names(l) = "Tinaye"
NB: Howevet most progr.rmming languages differ with Microsoft Visual Basic in handling arrays,
especially on the amount of memory allocated. For example, using fava, the following declaration:
Int [4 ]Names;
This array declaration creates exactly 4 memory spaces for the array Names. The indices ofthe array
range from 0 to 3 which are
Names[0], Names[1], Names[2] and Names[3]
I
When an array has been declared and the program is run, the procedure of creating it in the comput- t
t
er memory is as follows: I
Arrays simplifr the processing of similar data. An algorithm for getting 5 marks from the user and
storing them in the array Exam is shown below:
Dim Exam(4) As String
Dim i, Mark As Integer
r'ori=0To4
t otts r.WriteLine("Enter Mark " & i)
Mark = ( .otrsolt'.ReadLine0
t* (') ='o'k
*rt, ,
t ,r,tt de.Readkey)
One-dimensional anays
A one-dimensional array is declared using a single index and can be visually represented as a list. All
the examples which were given above for aray are one-dimensional. The following diagram shows
the visual representation of the array Names(4)in one dimension:
310 /
0 Austin
I Tinashe
2 Edith
3 Deborah
4 Daniel
Two-dimensional arrays
A two-dimensional array is declared using two indices and can be visually represented as a table. The
array presents data using their corresponding rows and columns as given below
Indices
0 I ) 3
0 Makombe Manasa M 4A
I Makamanzi Ison M 4B
2 Mununi Mary F 3C
3 Iuro Tinashe M 2C
4 Mutero Violet F 4C
The diagram above shows the visual representation ofa 2 dimensional array Names(4,3). The array
has 5 rows and 4 columns,
Each individual element can be referenced by its row and column indices. For example:
Names(O,0) is the data item "Makombd'
Names(2,I) is the item "Mary"
Names(I,2) is the item'M"
The following code creates an array called Names as given in the table above and allows
the user to
enter the array elements
Dim Names(4, j)
As String
Dim i, t As lnteger
Fori=0Ttt4
Fort=0To3
( ), solt'.Writeline(" I:nler nrray element " el i
tr & ", " e il
Names(i, t) = < ott*lc.Readline)
Next t
Next i
t ,,rt:rtb,ReadKey)
lnitialising an array
lnitialising involves giving starting values to array position, just like initialising variables. Initialising
is done to clear computer memory just making sure that there are no *y oth", values before the
prograrm executes.
/
A string array must contain a NULL value while numeric arrays start with 0 before program executes.
The keyword vbEmpty can also be used to denote that the array has no values in it or to clear elements
from an array. For example,
Studentmarks(Index) = v6g*O1t
vbEmpty is used to clear numeric values and not " 'i This is important to ensure that the array does not
contain results from a previous use or from elsewhere in the program.
The above code will create a one-dimensional array and place zeros in all the ten memory locations
of the array.
The above code will create an array with 6 rows and 4 columns and with no values in it.
3t3 ll
values without overriding
NB:- G is an extra memory location created to enable the Program to swap
to use as temporary
any one of them. It is impossible to swap 2 values without an extra memorylocation
storage for one ofthe values to be swapped'
ti" fillo*ing.ode creates the arruy, uilo*. "ntry ofvalues, sort the array elements and then display
the sorted array elements
Next Index
t )or sotc.WriteLine)
Const t.WriteLine('All Array Elernen\s Hove Been Entered")
Beep0
r )onsole.ReadKey)
(.rt tts ol,.Wtiteline0
BeeP0
t )trrsola.ReadKey0
t lonsott.WriteLine("Press F'nter lo sort the arrq' elements")
Beep0
t,' t t s,,l t.WtiteLine)
( ttt'tl, .WriteLine("l'ress enler tLt vie*'lhe sorted list")
t tttt:ti, .WriteLine)
, l,.ReadKey}
",,,,
3t4 /
'Displaying the sortd arrtty
elements
r^or Index = 0 To 9
t.o t,L,lt,.Write(ExamMark(Index) 6,, ")
Next Index
t t : t. WriteLine}
r t t L, I
t ,,tts,,lr'.ReAdKey)
array as follows:
t
ReDim Names(S) As String
315 /
re-create a dynamic array, its contents are reset to 0 (or to an empty string) and you lose the data it
contains. If you want to resize an array without losing its contents, use the ReDim Preserve command:
ReDim Preserve Named20) As String
Interface Design
User interface refeis to the environment presented to the user by the software to enable the user to
communicate with the comPuter. It is the way by which the user gives commands to the comPuter'
Common user interfaces are
. Graphical user interface
. Menu driven interface
. Command driven interface
. Form based interface
Advantages ofGUI:
. It is faster to give/select commands by just clicking.
. It is easier for a novice (beginner) to use the system right away'
. It is user friendly (this is an interface that is easy to learn, understand and to use).
. There is no need for users to remember commands of the language'
. It avoids t)?ing errors since no typing is involved.
. It is easierand faster for user to switch between programs and files'
. Most of them are attractive
Disadvantages of GUI:
. The iins occupy a lot of disk storage space that might be used for storage ofdata.
. Occupies more main memory than command driven interfaces'
. Run slowly in complex graphics and when many windows are oPen'
. Irritate to use for simpli tasks due to a greater number of operations needed.
. Usually only predefined choices are available'
316 I
The user has to remember the commands to be typed when performing a specific task. The
com-
mands are abbreviated and are short e.g. Del (for delete), copy, print, etc. Command Line interface is
ideal. for programmers and technically competent personnel. '1
l
l. Cash-out
2. Send Money
3. Balance Enquiry
4. ChangePIN
My Option Is: _
The user has to enter 1,2,3 or 4 and then press enter on the keyboard.
317
so forth. The user interacts with the application by selecting one of a number of possible values, and
by entering text into the fields that accept it. The following is an example ofa form based interface:
[,]€nbct*tp
c'o" I o"H" I
Pasod ad Popotle:
Lb..l-- ord'gc tud I
I Od Parord:. Cd p,pr.,i* |
, old Peirsd{
' Fndt.hcr
I
I
|bi.i hd... I \ I
l
L
lrl
3r8 I
. Legibility: with all options clearly shown
. Has online help
. Displays clear and informative messages when one makes a mistake
l{rf..;;tlbir t?r!,'. ;t
,@ E l6rod fqlt! Aftkiio.
AFFbror.rir. (elMd.t .
L!l
t{
iE
s eiP.l'f,I lfva I $d &pkrtion
vbj
Console Application
This. allows the user to develop programs that mostly use menu driven interfaces. Most of the examples
used in this book are console applicatlons.
3t9
Console mode uses the words for use.
Task Instruction
Accepting input data through the keyboard Console.Readline0
entry Inputbox0
Displaying data on the screen Console.Writeline0/Console.Write0
MsgBox0
To wait for a key press while displaying result Console.Readkey$
!.1 1l !r r, '
320
I
Input Form
An input form is designed for reading by the computer
system. It usuauy displays controls with
values, allowing the user to enter data Jn no
ii so that th'";;;g;"- ."" read. The system may even varidate
data on input forms.
Output Form
This is used to display data stored in the computer
system. Data can be displayed in contrors
textboxes, labels, list boxes, reports, etc. The rike
o'tput design ot a system depends on the form of data
and how the user wants it presented.
Example
Consider the following StaffDetails database table:
t7/07/t990
18/tLlt992 13112/2018
Possible Answer
a.
Field Narne Data Tlpe Size
EmployeelD Text/String 5
Surname Text/String/Alphabetic 25
DOB Date 8
DateEmployed Date 8
Sex Text/String/Alphabetic/Char I
Department Text/String/Alphabgtic 25
321
.-, firnsffi.l3
Employee ID
Sumame
Date of Blrth
Date Employed
5ex
Department
l --- t
L 51":1t" I
322
I
I
Od. Stur.. Co.tgu.tbn wod
I
I:rr14i I (;; tt
AddConnaction''".r4*.n
Drta lourcc
Microsoft Accrss Daabrsc Fila (OLE DB)
lusword:
' lrvc my pa:sword
323
Click Open
Click Test Connection and wait for a confirmation message. Continue if it says Connection
Succeeded, otherwise you vae to restart the process.
Click OK
Click OK again
Click Next
Click No
Click Next
Click boxes on the left ofboth Tables and Views to place tick in them
Click Finish. The data source will be displayed as follows:
,r &$ t
. r! khoob.t.!.rGo*.Sd
d anrpldy..ID
:- DOa
:a Drl.fmplorrd
*f@:i
Click Black down arrow on the right side of StaffDetails table and click on Details
Click the arrow on the left of StafiDetails and all the fields will be displayed.
Drag each field below StaffDetails, one by one, and droP each one on the appropriate textbc
on the Form you have designed. For example, drag EmployeelD and Drop it on the Emplolc'
ID text box on the form
Run you VB.Net Project. The first record will be displayed on the form as follows:
324
I
STAFF DETAISFOHilI
Employee ID 00234
Sumame &,nhdu
File Handling
A fi.le is a collection of data stored in a disk with a specific name and a directory path. When a file is
opened for reading or writing, it becomes a stream, hence FileStream.
Deslitop.
Before producing code to create the ExamsFile, letb perform the following:
. On the Desllop, create a folder and name it Exams.
One then needs to know the path that the computer would follow in order to open a file in the Exams
folder. This path differs from one computer to the other. If you are not sure oi the path, check it by
perform the following:
. Right click the Exams folder you have created on the Desktop
. Click on Properties
. Click the General Tab
. The path is on the right side of Location, just copy as it is.
!
325
I
,
s.or.y I Pcvlod v.arlz c!ron!.
NB:-The path you get for your folder is the one that you are supposed to use in all examples that we
are going to work with. It replaces whatever path is given in this book.
326
.l
lr r
i./
NB:- check in the Exams forder on the Desktop, there must be
a text 6le created inside it.
The following code can also be used to create a new text file:
lmports System
Imports System.IO
Imports System.Text
Usingfs
End Using
End rJ
File.Create Command
The Statement File.Create is used to create a new file in the given path.
Ifthere exist a file with the
same name in the path given, the existing file deleted.
FileStream Command
FileStream allows one to move data to and from the stream as arrays
of bytes. A stream is basically a
sequence of bytes passing through a communication path. There
are two main stream types:
327
. Input stream: is used for reading data from file (read operation) and the
. Output stream: is used for writing into the file (write operation).
VB.Net Namespaces
A namespace is a logical grouping ofclasses for the purpose of identification. Namespaces are a way
oforganiiing class librariis into a logical grouping according to their functionaliry usability as well as
category they belong to. Every language includes its own default namespaces for programs. However,
programmers can create their own namesPaces in .Net languages.
In order to access the functionalities of each namespace, the programmer must sPecifr the namespace
class in the code. However basic operations are already included in the default namespace and therefore
do not need to be defned. Only complex operations warrant the namespace to be includedjn the code.
The System.IO namespace contains classes used to perform a number of operations on files, for
example:
. Creating files
. Deleting 6les
. Reading from frles
. Writing to files
. Closing files
The following are I/O namespace classes for file operations and their functions:
328
/
In this chapter, we will use the Filestream class in performing most file operations.
FileStream Class
The FileStream class in the System-.IO namespace helps in reading from, writing to and closing files,
One needs to create a FileStream object in order to create a new file or open an &sting 61e. ThJsyntax
for creating a FileStream object is as follows:
For example, code for creating a FileStream object Fl for reading a file named ExamsFile.txt;
Dim fl
As FileStream = New FileStream("ExamsFile.txt'l FileMode.OpenOrCreate, FileAccess.
ReadWrite)
FileMode enumerator
It defines various methods for opening files. Common FileMode enumerators are:
. Append - It opens an existing file and puts cursor at the end of file, or creates the file, if the
file does not exist.
. Create - It creates a new file.
. CreateNew - It specifes to the operating system that it should create a new file.
. Open - It opens an existing file.
. OPenOrCreate - It specifies to the operating system that it should open a file if it exists,
otherwise it should create a new file.
. Truncate - It opens an existing fle and truncates its size to zero bytes
FileAccess eneumerator
It specifies that the file must be opened for:
. Read: Opens a file for reading
. ReadWrite: Opens a file for reading and writing
. \drite: Opens a 6le for writing
Writing to a Text File
We have already provided the code for creating a text file. The fi.le doesn t have anything in it. Let's look
how we can add text to a text file.
Let's assume thatyou are required to provide VB.net code that will write the following in the ExamsFile,
which already exist in the computer:
My name is Micheilla
The eldest in our family is Sandra
Second is Marian
Our only brother, Tinaye, is the third.
I am the last born
Code
Imports System
Imports System.IO
329
hnports System.Text
Public Class Lt, rt ;
Private Sub cmdRutlcorntnand-Click(ByVal sender As System.Ob.iect, ByVal e As .....
Dim fiIe As System.IO.ttrt'am \\\ itet
fle=My.Computer.FileSystem.OpenTextFileWriter("(.: \ [./se r.s \ A drr r ir \I)esfttop\Exans\
I:. x om s t' il e. I x t ",'Ii ue )
file.WriteLine("M1, nante is Micheilla" )
file.Writeline("The eldest in our .family is Sandra")
fiIe.Writeline(" Se c ond i s M arian" )
file.WriteLine("Our only brother, T-itm1,e, is the third.")
fle.WriteLine("1 anr the last bori')
file.Close)
End Sub
End Class
NB:-text can also be entered in a textbox, for example in textbox2. The file writing code would tbcr
be as follows:
file. Wr it e Line (Textb o x2. Te x t )
Note that the above example shows one of the numerous ways of writing to a text file. The follorf
code checks if the file exists, it does, it deletes it and creates a new one and then writes to it.
Dim FILENAME As String = "C:\Users\Adm in\Desktop\Exams\ExamsFile.txt'
IJ System.IO.File.Exists(FILENAME) ='I'rue Then
Dim objWriter As New System.IO.St renn \\1 ||r(FILENAME) 'Creates a new text .file
deletes an existing one.
obj Wr it er. Wr ite (Text B o x 1. Text )
objWriter.Close)
,\lrr.s.srrgt'Ilo-r.Show("Tbxt written to fle" )
Else
Mcs.sr13t'Iio-t.Shor ("File Does Not Exist")
End I
Howevet in order to add new text without deleting existing text, one must oPen the file for Appe{
The following code illustrates this.
330
I
Reading and displaying text from a file
The streamReader class is used read text from a text
file. The following code illustrates the use ofthe
StreamReader class.
Dim fleReader As System.IO.,\i r,., it ti 11., rriti
fiIeReader = My..Computer.FileSystem.OpenTextFileReader(,,(.:\Ltsers\Arlntin\I)esktolt\
Exant s\ E xttrn sJr le. t x t" )
Dim stringReader As String
stringReader = fleReader.Readline( )
MsgBox("7he f rst line of'the fle is ,, & stringReader
The above code reads only the first line from the file, so does
the folrowing code.
If l:ilt.Exists("C:\lJsers\Adtnin\Desktop\Exants\ExtuttsFile.trt,,) Thetr
Using tr As TextReader = New StreamReader("C:\Llsers\Admiir\Desktop\Exanrs\b)xttrn -
sFile.txt")
A ,-r.irig3 1J1,_s.Sft (tr.ReailLine( ) )
fu ew
End Using
End If
Structures in VB.Net
Structures can be defined as a tool for. handling a group oflogically
related data items. They are user-
defined and provide a method for packing toge-the-. dal of
di-r.rent types. st
to classes' Like classes, they too can contain members such as fields
u";;;;-;*ry
similar
and methods. The main difference
between classes and structures is, classes are reference tyPes
and stru.tur., *a typ., In practical
terms, structures are used for smaller lightweight ob.lects that ""tu"
u-sed for larger objects that are expected io exist in
do not persist fo. classes are lo{;l
Visual Basic .NET with the Structure keyword.
memory for long p.ii"ar. *"
a".r-i. structure in
"
331
End of chapter questions
Theory Questions
l.Explain the terms
a. data encapsulation
b. inheritance
c. Polymorphism
when applied to programming in an object oriented programming language. t4l
6. Programs can be designed in modular form. Discuss the advantages and disadvantages of
designing programs in modular form. tsl
7. Describe, using a diagram, the way that this problem can be split into modules to prepare il
for coding. tsl
8. (a) Explain why a program, written in a high level language, needs to be translated before it
run on a computer. l2l
(b) Describe the difference between interpretation and the compilation ofa high level language pro
gram. t4l
9. Explain how errors in the
a) reserved words,
b) variables
Used in high level language instructions are recognised by the translator program. [4]
12' Explain why the program may fail to run or may produce incorrect
.
that has been done.
results, despite the testing
l2t
13' when a computer runs a progr.rm, the program may fair to run successfully
because there are
errors in the code.
Describe two types oferror that may be present, gtving an
example of each.
t6l
l4'. . Explain why an interPreter would be preferred to a compiler as a translator when writing a
high level language program.
tsl
Outputdata( )
Getpayscale( )
Geresponsibility( )
333 /
Practical Questions
1. Write an iterative program that computes the product ofany 2 numbers through repeated
addition.
2. Write a program that accepts a positive integer and then output the number of digits in the
number.
3. Write a program that accepts a string and then displays the number ofcharacters in the string.
4. Write a program that accepts an integer and then display the sum ofthe digits in the number,
for examples
Number Entered is: 2476
is:
Sum of digits 19
5. Write a program that accepts a string and determines whether the string is a palindrome of not
6. Write a recursive function that computes multiples of a given positive number.
7. Write a program that accepts a positive whole number and then displays its binaryequivalent
8. Write a recursive program that outputs the Fibonacci sequence up to a certain number, n,
entered through the keyboard.
9. Write an iterative program that outputs the Fibonacci sequence up to 500.
334
I