0% found this document useful (0 votes)
4 views55 pages

Chapter 7 Programming

Chapter 7 focuses on programming, detailing features of high-level languages, control structures, and data manipulation. It discusses types of programming languages, including low-level languages like machine and assembly languages, and high-level languages that are easier to understand and use. The chapter also covers programming paradigms, object-oriented programming, and the importance of variables and constants in coding.

Uploaded by

chiyanjapeter7
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)
4 views55 pages

Chapter 7 Programming

Chapter 7 focuses on programming, detailing features of high-level languages, control structures, and data manipulation. It discusses types of programming languages, including low-level languages like machine and assembly languages, and high-level languages that are easier to understand and use. The chapter also covers programming paradigms, object-oriented programming, and the importance of variables and constants in coding.

Uploaded by

chiyanjapeter7
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/ 55

CHAPTER 7:

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

Ilpes of Programming Languages

l. Low Level Languages (IIL):


. These are programming languages used to write programs in machine code (i.e in ls and (b)
or in mnemonic codes and symbolic addresses.
. Low level languages are machine oriented (machine specific).
. There are two types oflow level programming languages:
a. Machine Language
b. Assembly Language.

a, Machine Code (Language) 1:

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

Application: A$sembly language is used in:


. coding opelating systems
. coding device drivers
. coding programs for embedded systems like DVD players, decoders, etc.
. coding encryption software

Advantages of Assembly language:


. One assembly language instruction corresponds to one machine code instruction and therefore
translation is easier and faster to code.
. Programs run faster since they are close to machine code.
. They occupy very small disk storage space hence are economical to use.
. Easier for a programmer to use than machine language.
f
isadvantages of Assembly Language
'f"fr
D
. They are very difficult to learn.
. They are very diftcult to understand.
. Takes too long to develop working programs.
. Th.y can be machine dependent (machine oriented) unless the machines use the same
processor chip.

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.

Facilities of High Level Languages


The following facilities ofhigh level languages are not found in low level languages
. Selection structures
. Iteration structures
. Built-in routines to simplify input and output, e.g.. INPUI PRINT, PRINTLN, etc in BAS C.
. Built-in functions like sqr, sqrt, val, etc.
. Data structures like strings, arrays, records, etc.
. User-definedfunctions.

Advantages of High Level Languages:


. They are easier to understand since they are written in English'like statements which are il
readable.
. They are easier tolearn. .k a
. It is easier to work with, that is to correct errors (debug) and to testprograms. S
. They are problem oriented and therefore can be used on any computer (not machine depeni{

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.

. Such programming paradigms are as follows:


* Imperative/procedurallanguages
* Declarativelanguages
* General purpose languages
r Special purpose languages
* Object oriented languages (OOp)

l. Imperative /Procedural Programming languages


. These are high level language programs in which the programmer specifies how the program
is to be executed, following a predefined execution sequence.
' The programmer has to write instructions (in source code) that are to be strictly followed
when performing a certain task.
. The programmer shows steps in the order ofexecution, providing a set ofdata.
' The order of statements is very important and is to be obediently followed by the computer
when performing a task.
. Examples include C, Pascal, COBOL, BASIC, etc.
. Imperative programming languages have the following features;
* built-in data types like integers, character, string, Boolean, etc
* user defned data types records, arrays, etc
* declarations for variables,likearrays, constants, functions, procedures, etc.
* programming statements like assignments, control structures, procedure calls, function
calls, etc.

) Declarative Programming Languages


These are programming languages that states what is to be done rather than how to do it.
The programmer states the facts and rules associated with the problem.
The order ofstating the rules and facts is not important.
Adding new rules, modifring existing ones and deleting some rules is very easy.
They do not use loops, selection structures or procedures.
They can also be called Very High Level programming languages or 4GL languages.
They have the following benefits:
* Makes it easier to progr:rm computer applications.
* Allow alternate methods ofdeveloping software, e.g. prototyping.
* One 4GL code is equivalent to several lines of3GL languages code.
* Prograrnmer productivity is increased.
Application: mostly used in designing expert systems.
Examples of declarative languages are Prolog (Programming in Logic)

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:

* Real-time control facilities: Programmer specifies times/frequency at which certain actions


are to be performed, e.g. taking readings after every 3 seconds for sensors. Programmerr
must also program timeout if the sensor fails to take reading in the specified interval and
treat this as a fault and take appropriate action'
* Interaction with hardware interfaces: language must contain instructions to monitc
devices like sensors and control actuators.
* Ability to support concurrent programming: languages must allow two or more actions to
take Place at the same time'

5. Object Oriented Programming languages (OOP)


It is a software design method in which programmers use classes and objects and implement conc$
like inheritance, polymorphism and encapsulation. Each Object has data items with all the possibL
processing on the data item attached to it (have states and methods). Exarnples of OOP languagrr
include Visual Basic.Net, C++, Java, Object Pascal, Common Lisp, Scheme, Perl, Python, Ruby' etc-
More details about OOP are dealt with in Book 6.

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

Features of High Level Programming Languages


High level progr-amming lango"g.s h".'"i t"tiity of features. Howeve! the following will be loolC
at;bperators, Variables, Constants, Expressions, Statements, Control structure and Block structurs

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.

Characteristics of valid variables


Visual basic.net variables have the following naming conventions:
' Variables must not be reserved words. A reserved word is a keyword with a special meaning in
the programming language, for example, IF, Else, Val, DIM, etc.
' Variables must be unique in the procedure orprogram theyare found.Iftwo differentprocedures
have the same variable declared in them and they will be treated as separate memory locations
. Variable names, as are all identifiers, start with an alphabetic character.
. variables have I to 255 character range, which can be alphanumeric, as long as the first
character is alphabetic.
' Thay must be one word, no sPaces are allowed for variables. If two words are used as a
variable, they must be joined by and underscore ( _ ), with no spaces between the words, e.g.
Student-Surname, NOT Student-Surname. Alternatively, one may join the words as follows,
StudentSurname.
. Must not contain a period (.), exclamation mark (!), or the characteri @, &, $, # in the name.

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.

f)im number As Integer


l)im Namel As String
I)im x, Number_I, AmountOwed As Integer

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

These declarations must be done within their respective procedures or functions.

Syntax diagram of a variable:


. Syrtax diagrams are graphical representations ofthe structure ofvalid variables.
. They convey what is legal for variable(or identifiers) in a certain programming language as
shown below:

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

In this case, the value of Name will never change.

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.

Private Sub .....


Dim result As Integer
Dim Name As String
Result = 20
Name = "Kapondeni"
End Sub

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>

If (condition) Then (begin block I )


(end block t)
Else (begin block 2)

End If (eud block 2)


Each block can have several statements depending on the situation at hand

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,

Private Suh cmdSaveBeneficiary ()

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.

In-built functions are pre-defined procedures ofa programming language


that returns a value, e.g. val
(returns a numeric value ofa string), MsgBox (creates o ttr"r."!.
bJ* oi the screen), Abs (returns an
absolute value of a number), etc. visual Basic has in-built date irnctions,
string iu*iiorrr,
functions, etc. "orru..rion

Task
Identifi vB.net inbuilt functions and explain their use. you may include a code snippet on how they
are applied in VB.

A user-defined function is a procedure (module) that returns a value whenever it is called


and is
designed and coded by the programmer. A function can be private
or public. The following are
examples ofstructures of Public and private Functions.

Public Function count_rec(ByVal rs As Recordset) As Boolean


(Statements)

End Function

Private Function DateTime (Byval pl As String) As Date

(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:

Entcr M.mb.r Drtr to Search


t oK-l
carrd I

This type of interface is available both in console mode and in Windows form application

Input operations also include statements like


ID = Console.Readline ( )

This prompts the user to enter a value on a blank screen


(in console mode) and press enter to confrm-
entered through a forn
11t. irogr"* then reads the value entered on the screen. Data can be also
based interface, which will be discussed later in this chapter'

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'

MsgBox ("Recoril not Found")


It displays a message box with the message in brackets'

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

a,Sequence control structure


This is whereby instructions are executed in the order
they_ appear in a program without jumping
rePeating any one of them uP to the end of the program, or
statements are executed one after another
in the order they are and each instruction ir .*..utid only once.
It i,,i-;i;;JJ.,no]a, .orrn.ion.
Example:
Dim A, B, total As Integer
Console.writeline(.Enter
frst number")
A=Console.Readline}
Console.writeline ("Enter Second Number")
B = Console.readline( )
Total =A+ B
Console.Writeline "Total of number is " & Total)

The above instructions are strictly executed one


after the other until the end of the program.
b. SelectionStructure:
This allows one to choose the route to follow in order to
accomplish a specific task. Selection is writ-
ten using the IF....THEN...ELSE statement or the SELECT
CASE statement.

Dim A, B As Integer Dim A, B As Integer


A = (.ntsole Readline} A=<.,tt ts,,b.Readline ( )
B = < )on'olt,.ReadLine) B = t' o r t ; o I t.ReadLine}
IfA>B7hen If A> BThen t t,trstit.WriteLine(.' A is bigger")
{ tttr;rtlt.WriteLine(" A is bigger") IJA<BThen( ott:olL WriteLine(,,B is higger")
Else IJ A = B The n ( h n 5 o l t . WriteLine (.. N u tn bi is equal',
IfA<B7hen )
t t't t:r,lr .Read.Key)
t ,,tt,,,1. Writeline(' B is bigger" )
Else
t a ttsolt,.Writeline("Nunrbers nre equal',)
End If
End If
(.rrir-.o/r'

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.

Select CASE Statement


This is an alternative to the IF...THEN...ELSE statement but it is shorter. Let us assume one is given
the following question:

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

The programmer can then double click


the Run button and type the fo'owing code:
Dim mark As Integer
Dim grade As Char
mark = VaI(TextB ox 1.Text )
Select Case mark
Case 0 To 33
grade = "IJ"
TextBox2.Tbxt = grade
Case 34 To <!4
grade = "E"
TextBox2.Text = grade
Case 45 To 49
grade = "D"
TextBox2.Text = grade
Case 50 To 59
gtade = "(i'
TextBox2.Text = grade
Case 60 'lb 74
grade = "8"
TextBox2.Text = grade
Case 75 To 100
grade = 'A
TextBox2.Text = grade
Case Else
TbxtBox2.Text ,,ln
= alid Mark"
End Select

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:

FOR {variableJ = {starting value} to {ending value} DO


Statement | 1
Statement 2 /
looPbody
)
NEXI {variable}

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:

Dim Average As Double


Dim I, sum, number As Integer
sum=0
Average = 0
ForI=1'Ib5
(,ott:r'lr WriteLine("Enler Nunher " 6 l)
number = t )ansolt.ReadLine)
sutn=sum+number
Nuct l
Average=Sum/5
r', t t s, b.WriteLine0
t t

t .L,tr .alc.WriteLine("'llrc suttt o! nunhers is " & sum)


t . r' n s .WriteLine}
t' 1,
t .ru t,t'i, .WriteLine("'lhe at'ernge o.J' nwnbers is " & Average)
t
',nst,l,.ReAdKey)

294
/
'/
An IF statement may also include the statements, Continue for and Exit for
in them as given below:

Dim i, A, sum As Integer


Fori=IToS
t,, : r,l t WriteLine(,'F,nter n unfu er,, )
tt

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

The Exit For statement forces the For loop to terminate.

Repeat... Until Structure


This_is a looping structure that repeatedly executes the loop body
when the condition set is FALSE
until it becomes TRUE. The number of reperition,
is executed at least once. The syntax is as follows:
-"y not b. krrown in advance and the loop body

Using VB.Net, the repeat ...until loop has many variations, which are as
follows:

Repeat
Statement I
Statement 2 Loopbody

Until {Condition}
I
Do

Loop Until {Condition}

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.

i.rtn',i,ltf3leadKey Dim Average As Double


Dim count, sum, number As Integer
sum=0
Average = 0
count = I
Do
t rti,.r,ic.WriteLine ("Enttr Nunher' 6 count)
29s
number = ( )t r s oL.. Readline ( )
t

sum = sutft + umber


couflt= count + I
Loop Until count > 5
Average=sum/5
( il\il(..Writeline ( )
t tt t:,, tli.WriteLine ("'lhe sum of nuntbers is " dz sum)
,

( 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:

Dim numben Sum, Average, Count As Integer


Sum=0
Average = 0
Count = 0
Do
Count =Count + 1
( )onsolt,.WriteLine("Enter Number " &
Count & " (999 to end")
numb er = t) o n s o I t. ReadLine( )
Sum=Sum+number
Loop Until (number = 999)
Sum=Sum-999
Average = Sum / (Count - l)
Oonsole.Writeline("The sum is " & Sum)
( )ottsolt.WriteLine("'lhe average is " & Average)

t)tttsole.ReadKey)

In the above program:


. Count records the number oftimes the loop body executes.
. 999 is used to stop further data entry through the keyboard and thereby ending the loop. If
entered, such a value that stops further data entry through the keyboard thereby terminating
a loop is called a Rogue value or sentinel.
. The condition here is {Number = 999}. The loop exits when the number 999 is entered. If999 is
part of the number to be entered in this program, then the user has to split it into two numbers,
that is 999 = 990 + 9, therefore can be entered separately as 990 and 9.

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.

While ... End While Structure


This is a looPing structure in which the loop body is repeatedly executed when the condition set is I
TRUE until it becomes FALSE. It is used when the number of repetitions is not known in advance.
The condition set is tested first before execution of the loop body. Therefore the loop body may not

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 example ofthe program is as follows:

Dim number, Sum, Average, Count As Integrr


Sum =0
Average = 0
Count = 0
While Count < 5
Count = Count + 1
c.Writeline(" Enter N unber " & Count)
( ;on : o l

number = ( )rtr solc.Readline)


Sum=Sum+number
End While
Average = Sum / Count
(.)ortso|t.WriteLine("'.lhe sum is " 6 Sum)
()ortsolt:.WriteLine("7he average is " & Average)
t hns,tle.ReadKey)

An Exit While statement can be inserted at any point within the loop body in order to terminate the
loop when the need arises.

Differences between the Repeat...until and the while...ENDWHILE structures

Repeat Until Loop While Endwhile Loop


I Loop body is executed when the condition set Loop body is executed when the condi-
is FALSE until it becomes TRUE tion set is TRUE until it becomes FALSE
2 Loop body is executed at least once Loop body may not be executed at all
3 Condition is tested well after execution ofloop Condition is tested before execution of
body loop body

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)+

Possible answer (Console Mode)

Imports System. ( )ottsolt


l\'[od t:l
Sub Main)
Dim column, row As lnteger
Forrow=lToB
For column = row 7b 8
'
Write(" ")
Nexl column
WriteLine)
Next row
ReailLine0
End Sub
F.nd Module
The program uses nested For and the result is as follows

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

(d) Outputs the following pascal,s triangle

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

NB: It is also acceptable to write Sub Main 0 calling statements as follows:

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

sulr.Writeline("Enler Second Nuntlter ")


( .n tr

second = ( ;ott:olt.ReadLine}
't^irsl and Second are Actual paranteters

Function calcTotal(ByVal a As Integer, ByVal b As Integer)


calcTotal=a+b
End Function
'a and b are
formal parantelers since they receive values from frst and second respectiyell,

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)

Passing Parameters by Value


Passing by value is whereby the actual value (or value ofa variable) is searched
for (e.g 20), copied and
passed to a variable in another module. It therefore implies that the
vahe, of th. ri p"r"m"t.,
the formal parameter will be the same. However, the variables will be pointing ""i to ditrerent menory"rrd
locations in the computer system.
Visual Basic.Net uses the statement ByVat to indicate that the parameter passing used
is by value, as
shown below:
Sub acceptNumbers)
Dim first, sum, second As Integer
(. o t s o l t.WriteLine(" hxe r .,
t
li rst n unbe r )
first = ( o t t s ol t,.Reailline}
;

Console.WriteLine("Enter Second Number,,)


second = t )onsole.ReadLine)

i:unction calcTotal(ByVal A As Integer, ByVal b As Integer)


calcTotal=a+b
End Function

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.

Passing Parameters by reference


P-assing parameters by reference is where\ the address ofthe value is passed, allowing it to be altered
if necessary. Visual Basic uses the keyword ByRef to indicate that parameter is belng passed by
reference, as shown below.

P r i v at e S ub acceptNumb ers0

sum = calcTotal(first, second)

End Sub

Function calcTotal(ByRef A As Integen ByRef B As Integer)


ealcTotal=A+B
End Function

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.

Thus, in passing parameter by reference,


' The actual address is copied to the formal parameter so that the actual
and formal parameter
point to the same location.
' When value of the formal parameter is changed, the value of the actual parameter
is also
changed to assume the same value.

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

Structured programming allows use ofconstructs like selection and iteration


and avoid use ofGO
TO statements.

Structured programming facilitates modularisation. It involves the concept of step-wise


refnement.
This is whereby a program is split into several, simpler subtasks called
modules *ii"h *itt be easier
to solve. The modules are also called procedures, routines, sub-routines or functions.
The splitting of
a problem into a series of self-contained modules is called modularisation (modular
programming).

Advantages of modularisation (modular programming)


' Minimises coding since a module can be called many times from different modules using
par.imeters can be used to pass data within the program.
. Programmer can concentrate at one simpler task at a time.
. Modules are simpler and easier to understand and to solve than complex problems,
. Modules are easier to test and to debug and therefore lessening testirg time.
.' Many programmers are employed, one on each of the modules.
Program modification is easier since changes are isolated with specific modules.

. More experienced programmers can be assigned complex modules.


. It saves programming time by sharing tasks.
. A large project will be easier to monitor and control.
. It is easier to update (modift) modules than the whole program at large.
. Fewer bugs since each set of programming commands is shorter
. Allows library programs to be inserted

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.

Bottom-up approach to Programming


It refers to a style of programming where an application is designed or constructed starting with
existing primitives of the programming language, and constructing gradually more and more
complicated features, until the all of the application has been written. This is the opposite of top-
down programming. Bottom-up emphasises on coding and early testing, which can beiin as soon as
the first module has been specified. In bottom up programming, you identiff lower-lJvel tools that
you c.rn compose to become a bigger Program. You think of the basic functionality and the parts
you're going to need and build them up. It emphasises on developing the actors and their methods,
and then joining them together to make a coherent whole. It st;ts;th the component parts and
repeatedly combines them to achieve the general concept. In other words, it starts with the specifrc
and continually combines it until it reaches the abstract.

Source Code and Object Code

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

Written in English like statements Written in Is and (machine code) or in mne_


0s

Easier to work with

Are problem oriented and can be used on Machine oriented

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_

Visual Basic,Net Data Tlres


Visual Basic.Net data types describe the nature of data handled
by its programs. vB.Net data types
include integer, string or complex (arrays, lists, records, etc.).

.'
Data types are declared at theteginning or at some point inside
the program code.
Data types for variables must be properly declared.

a. Numeric data typee


l. Integer
. Used to represent whole numbers, positive or negative, and occupy 2 bytes ofmemory.
. Decimal values will be rounded to the nearest whole number.
. Values accepted range from -32 76g to + 32 767. Default value is 0.
2. Byte
. Stored in a single 8-bit unsigned data value ranging from
0-255.
. Used to store binary data.
. Default value is a 0.

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.

b. String data gpes


l. String
. A string is data type that stores one or more characters, which can be alphabetic or alphanu-
meric.
. If a variable is declared as a string, it must not be used for daily life mathematical ialculations
because strings are not numbers.
. Strings are declared as follows:

Dim Name As String


. If a value of string variable is assigned within the program code, it must be enclosed in
quotes e.g.
Name = "Tungamirai"
Name = " "
. The second example will be a null (un-initialised) string. It is different from 0 or space but is
distinct in nature.
. Strings can be offixed length or variable length

Fixed length: has specified maximum number ofcharacters. E.g.


Dim Sname As String * 20
. The field will be allocated 20 spaces in the computer memory.
. Ifa name shorter than 20 characters is entered, blank spaces will remain unoccupied since
they would have been assigned to Sname already.
. Ifdata is too long than allocated space, the extra characters are cut.

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"

Declaration of arrays using VB.Net


Arrays are declared by stating the following parameters:
. array n:rme
. array size
. dimensions
. data type.

The size of the array is the maximum


number of elements that it can store. For example,
is a declaration ofthe array names the following

Dim Names(4) As String

The above declaration reserves,five rocations


in memory for an array cafled Names. The array
dimensional and stores string data. The is one_
,"-"
Dim Names(0 To 4) As String ".r"y "* i.o
be declared as

One may also declare the array as


Dim Names(l To 5) As String

The last option modifies the starting value


and the ending value of the indices, but the number
elements still remains the same. of

By default, this implies that the above decrared


array stores at most 5 elements. on running,
computer creates-s contiguous memory locations the
undlr the name "Names'l Thus Names will contain
5 Partitions' Each-memory
Partition will be accessed using an index, which is the address of the
memory space in the array.

In visual Basic, the number oferements stored in


an array is N_+ l,N being the number (subscript)
when declaring the array. Array index starts at used
Zero N, N being the number in the declaration
ofthe array. The index is also caled subscript, "1a arrays are subscripted
ti"r.for.
"nd data types. It is
not possible to exceed the upper limit or go below the lower limit on the array index values. You will
receive a "subscript out ofrange" error message ifyou try to do so.

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]

Creating an array in comPuter memory 1

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

. Name of array is determined


. Size of array is calculated
. Location of array is decided according to data type and size
. Locations are reserved for the array
. Size of array is stored in a table
. Lower bound ofthe array is stored in a table
. Upper bound of array is stored in a table
. Data type is stored in a table
. Address offirst element is stored in a table

Inserting data into an array


One rnay use the assignment statement or use looping structures. For example, the following state-
ment assigns data to the 4th element:
Names(3) = "KaPondeni"

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.

Code for initialising a one-dimensional numeric array


Assuming that we have an array called ExamMark and contains l0 elements, the code will be as
follow;
Dim ExamMark(9) As Integer
Dim Index As Integer
For Index = 0 To 9
ExamMark(Index) = 0
Next Index

The above code will create a one-dimensional array and place zeros in all the ten memory locations
of the array.

Code for initialising a two-dimensional string array


Let's assume that we have a two-dimensional array called StudentNames, it can be declared and
initialised as follows:

Din StudentNames(S, 3) As String


Dim Rowlndex, Columnlndex As lnteger
For Rowlndex = 0 To 5
For Columnlndex = 0 To 3
StudentNames(Rowlndex, Columnlndex) = " "
Nexl Columnlndex
Next Rowlndex

The above code will create an array with 6 rows and 4 columns and with no values in it.

Searching an Array Element


Searching ofdata is one ofthe most important operation. The following code uses serial searching to
determine if the element Value exists in array StudentMarks that contain 100 integer elements:
Dim lnden Value As Integer
Dim Flag As Boolean
Index = 0
Flag = Palt'
('uns dL.WriteLine("Enlcr lhe Value h be searched ")
Value = r ,on so[e.Readline)
Do
lf StudentMa*s(lndex) = Value'Ihen
Fhg = 71u'
\ tttt \|IL 'WriteLine)
3t2 I
( r ttt.'L,lt.Writeline(F,le nent
hns been Jbuntl,,)
End Il
Index= Index + l
Loop Until (Flag = 7yr"1 Or (Index > 99)
I-f Fllg = Falsc Tlten
Cons ole.WriteLine (,' I t em N ( )T
fo un d,,)
h.nd tJ
t.,,, t.,tir,.ReadKey}

The same code can be written using.input and


message boxes as given below:
Dim Studentmarlcs(99) As Inleger
Dim Index As Integer
Dim Flag As Boolenn
Dirn Value As Integer
Index = 0
Flag = Polt'
Value = InputBox(,,Enter item to Search.)
Do
If Studentmarks1nitex) = Value Then
MsgBox(Studeiltffiarl<s(Index) 6 ,, Has Been l:ourrd,,)
Flag = 7'7u'
End rf
Index = Index + I
Loop Until (Flag = True) Or (Index > Ugound(Studentmarks))
If Flag = Pal5g Vr.,
MsgBox(Value & ,, is N07. in the arroy,,)
End If
t ;ottso|t,,ReadKey0

uBound is a function that returns thelast array position


while LBound returns the first index position
in an array' These terms are normally ur.d *h.r, one
does not know the first and the last index
positions ofthe array.

Sorting Array Elements


The following code sorts ExamMark array
values in ascending order and displays the sorted
elements' The assumption is that the array ii". array
and values have been entered into
it. "l;til;;.reated
'CLtde
ftnsorting the array elenents
r"or y = LBoufld(ExamMark) To UBound(ExamMark)
I:or z = LBound(ExamMark) .to IJBound(ExamMark) _
1
If ExamMark(y) < ExamMark(z) Then
G = ExamMark(y)
E xamMark (y ) = ExamMark (z)
ExamMark(z) = e
Eld tf
Next z
Next y

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

Ditn ExamMark(9) As lnteger 'Oreate the arruy


Dim lndex, Y, z, G As lnteger
'Enlering values into the arraY
For Index = 0 To 9
(.tt t:rtlt.WtiteLine("e nler orru1'elemenl " dt lrtdex)
EmmMark(Index) = t tt t s t ll "'Readline) t

Next Index
t )or sotc.WriteLine)
Const t.WriteLine('All Array Elernen\s Hove Been Entered")
Beep0
r )onsole.ReadKey)
(.rt tts ol,.Wtiteline0

' Displaying the arra)' eletnenls enlered


For Index -- 0'lb 9
(.onsolt'.Write(ExamMark(Index) & " ")
Next Index
Co tt'ott'.WritiLine)

BeeP0
t )trrsola.ReadKey0
t lonsott.WriteLine("Press F'nter lo sort the arrq' elements")

'sorting the arraY elements


Fu, y J LBound(ExamMark) To lJBound(ExamMark) .
z = LBound(ExamMark)'Ib lJBound(ExaffiMa0 -
ir I
If ExamMark(Y) < ExamMatk(z) Then
G = ExamMark(y)
ExamMark(Y) = ExamMark(z)
ExamMark(z) -- G
End tf
Next z
Next y

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)

Deleting Array Elements


when deleting array elements' the comPuter must first
of all search for the element to be deleted. If the
value is found' it set the value of that memory location
to empty. Thus the element would have been
deleted. Ifthe element is not found, then there is
nothine to delete.
The following code deletes the value as per user
request.
Dim Flag As Boolean
Index = 0
Flag = Paltt
Value = InputBox(..Enter item to Delete,,)
Do
lf ExamMark(Index) = yo1u, 77rm
Fhg = 77u'
ExamMark(In ile x) = vb Empt
/
MsgBox(Value eh ,, Has lleen Deleted,,)
End If
Index = Index + I
Loop Until (Fhg = .Iiue) Or (Index > UBound(ExamMark))
If Fhg = Psks 7.,
MsgBox(varue & " is No''in the array. rhere is Nor-HrNG
to delete")
End If
t lnsole.ReadKey)

The algorithm first searches the element to delete,


and then remove it from the array.
NB:
' If the item is string, it repraces with empty spaces. However,
if it is numeric, it replaces with a
0.
' Deleting from an array is often difficult as elements need
to be shifted positions after dele-
tion. Howevet it is an effective method for deleting elements.

Dynamic Declaration of Arrays:


Arrays can also be declared dynamically so that the user
has to decide the size ofthe array when the
Program is running. The programmer does not need to specify the number or ,r.rrr*L
declaration stage. Dynamic declaration of arrays i, dorr.
during the
Dim Names( ) As String
Inside the module, one then needs toiedefine the
ar-fo oru.,

array as follows:
t
ReDim Names(S) As String

This allows the user to create the array when he/she


actually needs it, using a ReDim statement.
Dynarnic arrays can be re-created at will, each time with
a different number of items. When you

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

l. Graphical User Interface (GUI):


It is a way of communication between the user and the computer by use of Windows, Icons, Menus
and poiniers (WIMP) as supported by Microsoft Windows l0 oPerating system. The user moves a
mouse and points on required option and then clicks. It has commands in form oficons which have
the name oi the command or file below the icon. The mouse is the most used device in this system'
GUI is most suitable for novices, that is, beginners and users with lower computing skills.

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'

2, Command Driven Interface


the user
This is also called command Line or character based Interface. This type of interface allows
to type the command to be carried out by the computer through the keyboard as supported by MS-
nO'S. T'nus communication between the user and the computer is through typed commands.
The
command to be obeyed must be typed correctly; otherwise it will not be obeyed. It usually displays
prompt; which are .irur""t"r, dispiayed on computer screen to let the user know that a command is
required; e.g.
C:>-
This is the C-prompt, on which the user can type the command in front, e'g'
C: >copy:\computernotes'doc D:\KapondeniT

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

Advantages of Command Driven Interface; 1

. It saves disk storage space since there are no icons involved.


. It is very fast in executing the commands given once the user mastered the commands.
. It saves time if the user knows the commands by heart.
. Effective when troubleshooting hardware problems
Disadvantages of Command Driven Interface:
. It takes too long for the user to master all the commands by heart.
. It is less user-friendly.
. Do not tolerate mistakes, thus it's not a forgiving type of interface
. More suited to experienced users like programmers.
. Commands for difierent software packages are rarely the same and this will lead to mix-up of
commands by the user.
' It is intimidating for most computer users and beginners. Therefore is not the best for normal
apphcations
. Most users need manuals to refer as commands are easily forgotten.

3. Menu Driven Interface:


This type of interface displays a list ofoptions / commands from which the user has to choose one by
use ofthe mouse or keyboard. Below is an illustration ofa menu driven type ofinterface:

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.

Advantages of Menu Driven Interface:


. It is fast in carrying out task.
. The user does not need to remember the commands by heart.
. It is very easy to learn
. No need to consult manual
Disadvantages of Menu Driven Interface:
. The user is restricted to those few options available and thus is not flexible to use.
. The intended option can be a submenu, which may slow down operations
4. Form Based lnterface
In this case, the user is presented with a form to 6ll in the required details on.it. The form might
contain controls like labels, command button, textboxes, list boxes, radio buttons, option buttons and

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

u-r Ptrn' [- P"*"o't'


an* sJi
'[--- aot tr"-"'l------f,
f Only cr!d? a dclds I urcc dml ura thc f ol U:anfidd

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

Advantages of Form based interface


. Easy to design and to Program
. Available options are usually clear and easy to see' -
. It is easy to perform data validation on data entry forms
. Fast to enter data or to make choices
. Little or no training required and therefore is user friendly
. There are no commands to learn or remember
. Even ifyou dont know what to do, you can usually guess
your way around the options

Disadvantages of form based interface


'. Only limited oPtions Presented
Visually impaiied people might have trouble seeing the text or oPtions
. Not good for highly complex apPlications
. A poorly designed menu interface may be slow to use
. It can be irritating ifthere are too many menu screens to work through - users get annoyed
or bored if it takes too long
. Some forms may take long to load' especially in poorly designed systems
. The computer needs a lot of memory to store and run the forms
Characteristics of a Good User Interface
. Should have consistent menu structures
.Forgiving:shouldnotbetoostrictasuserscanmakemistakes.Thusshouldallowusersto
undo some actions.
. the same company
Familiar: should be similar especially for programs designed by
. A$ractive: Maybe by use of good colour, layout'-etc
. Efficient: musiperform functions faster and with less effort'
.Shouldbeclearintermsoflabellingandnamingitsuse.Namesshouldnotbevague

3r8 I
. Legibility: with all options clearly shown
. Has online help
. Displays clear and informative messages when one makes a mistake

Considerations when making user interfaces


When designing interface, the analyst should consider the following;
. Who will be using the system?
' Children at lower grades like ECD would prefer bigger, colourful and graphical
user inter-
face. This is not the case with cornputer techniciani.
. What knowledge do they have?
. How much on-line help is required
. What is the information that needs to be shown?
. How much information is needed?
. What is the best way of showing the information needed
. What colours should / should not be used?
. What other form of output is sensible?
. What technology is available?
. Costs of designing the interface as well as maintainability.

Visual Basic.Net allows users to design a number of user interfaces. However,


most Visual Basic.Net
programmers, usually beginners, prefer a form based type of interface with
GUI options on it.
vis'ral Basic allows developers to design systems in Console Mode or using the windows
Form
Application. The developer chooses these on the Start page as shown below:

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

lil'dl9ln Cla, li..|0

Ctlrrs\,t0r06tif 0a'Dehop,{d.hHCrtrE lytol


Lq.*sqtr
,/ C,*Cit brylaouh.

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$

Windows Form Application


This allows the user to develop form based interfaces for a system. The system will display the following
IDE when chosen

,. J^5 tr .i,....r.:., " ,9U,

!.1 1l !r r, '

The VB.Net IDE has the following windows


. Menu bar: Displays commands used to design an apPlication.
. Toolbox Window: Contains all the controls that can be placed on a form, e.g labels, textboxes,
radio buttons, etc
. Properties window: Allows the user to change or assign properties or characteristics to the
selected object or control, like, background colour, font type, etc. Press Ctrl + AIt + X to view
it if not displayed on the screen.
. Form designer window; Allows the user to place controls on a blank form
. Solution explorer window: It allows the user to view and navigate through objects placed in tbc
project, e.g. reports, forms, etc
. Team Explorer Window: used to manage work assigned to your or to your team.
. Code window: Allows the user to tyPe code to be run by the system
. Debug window / Error List window: shows a list of errors and warnings in the designed
program
. Object browser Window: Allows user to browse through objects, methods and events in ordcr
to see their properties. |ust press F2 to view it.
. Immediate window: used to debug, print variable values, execute statements, evaluatc
expressions, etc
Forms designed can be input or output forms.

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.

Designing a form based interface

Example
Consider the following StaffDetails database table:

t7/07/t990

18/tLlt992 13112/2018

a. Design a data structure for the table


t*- based interface for the table using a high level
programming language of your
l;o,?.o* "
c' create a database and the table above using a DBMS
tool. connect the form based interface
to the database table you have created.

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

b. Form Based Interface Using VB.Net

321
.-, firnsffi.l3

Employee ID

Sumame
Date of Blrth
Date Employed
5ex
Department

l --- t
L 51":1t" I

c. The steps are as follows;


click on the Data source option. (If not shown, click on Data and then
Add New Data
Source.)

Click Add New Data Source


Click on Database
Click on Next
Click on Data Set
Click Next. The following will be displayed.

322
I
I
Od. Stur.. Co.tgu.tbn wod
I

i ClE.n Y.u. g.i. c6hn.Glon

i *r.b d.r. .ffidon tlDld ttur .r?&.rbn e ro ffit ro oE 6r.b...t


- {.f1a9@;l

I:rr14i I (;; tt

Click on New Connection


Click on Microsoft Access Database File
Click Continue. The following will be displayed

AddConnaction''".r4*.n

to connect to thc sclcded datr sourca or <lick


Entar information
"Chrngr" to choos! . diffcrent drtr sourcr and/or provid!r.

Drta lourcc
Microsoft Accrss Daabrsc Fila (OLE DB)

Pdrbasc filc nrma:

Log on to thc drtlblse

llrcr nrmc: Admin

lusword:
' lrvc my pa:sword

On Database File Name, click on Browse


Select the Database 6le you have created

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:

fiE ldr vie Proj.tt Soild l.!r ArlF w'ndo* H.lp


:ra"Ji.J'dJ ) .. cr fr a

,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

Date of Blrtfi 7/17/1ys

Date Employed s /zsr8

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.

Creating text 6le


A tex file contains data that is alphabetic or alphanumeric only.
Let us assume that we want to create a text file named ExamsFile.brt in the Exams folder on the

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

lo.l.' Ap. iO 2315 A Oe 29 Ar,!

a F..d.n\ df,'"/ .etd !o rn.t


'h
fordd,l
}+<lcLn Adv.Gcd

The path indicated is C:\Users\Admin\Desktop.


The Exams folder is on the Deskop so its path is C:\Users\Admin\Desktop\Exams
The ExamsFile is to be created in the Exams folder, so its path would be C:\Users\Admin\Desktop\
Exams\ExamsFiIe.b<t
We shall use this path to create the ExamsFile using VB. Net.

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.

Lett now create the ExamsFile using VB.Net (2010)


. Create a Form in VB.Net
. On the form, add a command button control
. Double c[ck on the command button
. Tlpe the following VB code
Impolts Systefl
Imporx System.IO
Imports System.Text

Public Class I:or tn I


Private Sub cmdRun_Click(ByVal sender As System.( )lrir( t, ByVal e As....
Dim path As S/ring = "(l'\ [/se rs\Atlmin\Desktt p\Exams\I:.xdnsF'ile.lxt"
'Create or overwrite the Jile.
Dim fs As l:ilt\tr ir;,n = Fib.Create(path)
Iind Sub
F.nd Class

326
.l
lr r
i./
NB:- check in the Exams forder on the Desktop, there must be
a text 6le created inside it.

The statements, rmports System, imports System.IO,


Imp.rts System.Text must be found in every
file handling program.

The following code can also be used to create a new text file:
lmports System
Imports System.IO
Imports System.Text

Publie Class l,or tn 2


Private Sub Buttonl _Click(ByVal sender As System.( )lltttt. ByVal
e As ...
Dim fleName As String = "C:\users\Adntitt\Desktop\Exaits\F,xamsr^ile.lxt.,
Dimf As New t:ilt,trtli(fileName)
Try
'Check il already exists. lf yes, it k deleted.
fle
tf f.Exists Then
f.Deletee
End IJ
'Creating a new
fle
Usingfs As ltile St reut it = fi.Create}
End Using
Catch Ex As Exception
MsgBox("File cait be Created,,)
End Try
End Sub
End Class

The following can also be used


Dimfs As l.tlt.\!tt,uttt = Nothing
If (Not l:ilt.Exists("C:\LIsers\Ahnin\Desktop\Exarns\Exatnslrile.lxt")) Then
fs = I i t.Create(.,( ):\U sers\Ad n itr\D esktop\Exa nt s\Exa nr sFile.t xt,;)
I
I

Usingfs

End Using
End rJ

Explanations Using the First Code

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.

The following is a structure of different namesPaces in VB'Net

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.

VB.Net I/O classes


One can invoke a namespace by including the namespace in the VB.Net code first before any other
code can be written. The I/O system namespace is specified as:
Imports System.IO

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:

I/O Class Use


BinaryReader Reads primitive data from a binary file
BinaryWriter Write primitive data in binary format
BufferedStream Temporary storage for a stream of bytes
Directory For manipulating a directory structure
Directorylnfo Performing operations on directories
Drivelnfo Provides information for the drives
File Helps in manipulating files
FileInfo For performing operations on files
FileStream Used to read from and to write to any location in a file
MemoryStream For random access of streamed data stored in memory
Path Used to perform operations on path information
StreamReader Used for reading characters from a bpe stream
Streamwriter Used for writing characters to a stream
StringReader For reading from a string bufer
StringWriter For writing into a string bufer

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:

Dim <object-name> As FileStream = New Filestream(<file_name>, <FileMode Enumerator>,


<FileAccess Enumerator>, <Fileshare Enumerator>)

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.

Dim fleName As Slring = "C; \ Use rs\Adntin\Desktttp\Exams\ExatnsFile. txt"


Dimf As New I'ilelttl|(fileName)
Try
lJ s in g fs As.S/ r('.? r r/ I V r ilr'' = f . App endText)
fs. Wr it eLine (Te xt B o x 1. Text )
End Using
Calch Ex As I rrrr'r/iltr
MsgBox("File can'l be Wrilten to")
F.nd1iy

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

2. Distinguish between procedural languages and declarative languages. t4]

3. Explain the passing of parameters by reference and by value. t4]

a. (a) (i) Describe what is meant by sourcecode. 12)


(b) Explain why source code needs to be translated into objectcode. I2l
(c) State what is meant by the following types of programming error:
(i) syntax error trl
(ii) arithmetic error trl
(iii) semantic error trl
(iv) Logical error tll
S. (a) Explain how the translator program prepares the programmer's code into a program tha
the machine can run. 12)
(b) (i) Explain what is meant by a procedure. l2l
(ii) Describe how procedures and the programming construct 'telection" can be used to code a sim-'
ple menu system for a user. I3l

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]

10. Describe each of the following programming paradigms


a) Object-oriented, 12)
b) Declarative, l2l
332
I
I l. . An exam mark is passed as a parameter to a function. The function
uses a loop structure to
search for the mark in an array. It returns the details
searched can be passed either
found to ,t
"
."
irg pr"gr"ri. it"
*"rn r. u"
a. by value, or
b. by reference.
using this example, explain what is meant by a parameter being passed
by varue and by reference. [2]
Using examples from this function, explain what is
:..
(i) local variable,
-."rrt by "
(ii) Global variable.
I4t

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

15' In a particular object oriented programming language, the following


classes are defined

Outputdata( )
Getpayscale( )
Geresponsibility( )

With reference to the diagram


i. Data encapsulation
ii. Inheritance
I4l

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

You might also like