0% found this document useful (0 votes)
21 views34 pages

Cos 102 Problem Solving Techniques

Solving computer problems
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views34 pages

Cos 102 Problem Solving Techniques

Solving computer problems
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

lOMoARcPSD|55615542

COS 102 problem solving techniques

Computer science (Kwara State University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by ayodeji tobiloba ([email protected])
lOMoARcPSD|55615542

Problem Solving Techniques


In life, one major reason most people fail or encounter difficulty in their lives/endeavor
is that they they fail to follow an organized procedure, that is, they fail to plan. A recipe
provides a good example of a plan. The ingredients and amounts are determined by what
is to be prepared; the output determines the input and the processing. The recipe often
reduces the number of mistakes you might make if you tried to bake with no plan at all.
Many programmers particularly students in their first programming course frequently try
to write programs without making a careful plan. One complicated problem requires a
complex plan. It will however be observed that you spend much less time working on a
program if you devise a carefully thought out step-by-step plan and test before actually
writing the program.
Although a computer is a very powerful and versatile machine yet it has no IQ.
A computer is defined as an electronic device which accept data in a prescribed format,
stores the data, processes the data through some set of instructions called programs and
brings out the processed data as an output suitable for deriving meaningful and logical
conclusion but has earlier stated it has no IQ. A computer performs man tasks exactly in
the manner as instructed or directed by the programmer. Hence, most of the
responsibilities of programming is placed on the user to instruct the computer in a
correct and precise form so that the machine is able to perform the required job in a
proper manner.
In order to instruct a computer correctly, the user must have a dear understanding
of the problem to be solved. Problem solving is a process which is an integral part of
work and life, it is the means of reaching a desired situation from a current situation.
Many programmers plan their programs using a sequence of steps referred to as the
program development cycle. This cycle is made up of five(5) stages: Analysis, Design,
Coding, Testing and debugging and documentation.

Program Development Cycle


1. Analyze (Definition of the problem); This is the first step in the process of program
development and it involves a thorough understanding and identification of the problem
for which is the program or software is to be developed. In the step, the programmer has
to be able to define the problem formally. He should understand what the program
should do, that is, what the output should be. He should have a clear idea of all factors
like the input/output, processing requirement, memory requirement etc. A clear
understanding of what the output should be must be understood here.
If this stage is not clearly/properly done, one might be solving a wrong problem. It
may be helpful at times to underline phrases in the problem statement that identifies the
inputs and outputs such that a list of formulas that specifies the relationship.
Compute and display the total cost of oranges given the number of pounds of
oranges purchased and the cost per pound of oranges.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Problem inputs
Quantity of oranges purchased (in pounds)
Cost per pound of apples (in naira per pound)
Output
Total cost of oranges (in naira).
Once the inputs and output(s) are known, develop a list of formulas that specify
relationship between the:
Total cost = unit cost * number of units
Substituting the variables for our particular problem yields the formula to generate the
answer (output)

2. Design (Planning the problem solution): Here, a logical sequence of precise steps that
solve the problem at hand called an algorithm is employed.
Algorithms are finite sequence of well-defined computer implementable
instructions, typically to solve a class of problem or perform a computation. Algorithms
are complete, unambiguous finite number of logical steps for solving specific terms in
mathematics or computer science.
Algorithm must be finite (terminates in a finite number of steps), defined (each step of
the algorithm must be effective, that is, it should be stated), effective (each step must be
effective, that is, it should be primitive and easily convertible into program statement),
solve problems of a specific type completely for any data input, be able to make one or
more quantities as input data and produce one or more output values.
Every details including obvious steps should appear in the algorithm. Three
popular methods used to implement an algorithm includes flowcharts, pseudocodes and
hierarchy charts. Writhing of algorithm is about the most difficult part of a problem
solving process and as such a programmer should not attempt to solve every detail of the
problem at the beginning. To avoid mistakes, discipline yourself to use the top-down
design (hierarchy). Summary, all of small tasks the computer can perform to solve the
problem. However, the use of representative data to test the logic of the algorithm by
hand to ensure that it is correct is advised.

Hierarchy Chart also called the structured charts, HIPO (Hierarchy Plus Input-Process-
Output) charts depicts the process of organizing a program but omitting the specific
processing logic, The chart describes what each part/module of the program does and the
show how the module relate to each other but the details of how the modules work are
omitted. The chart is read from top to bottom and from left to right with the possibility
of each module being subdivided into a succession (sequence) of submodules that
branch out under it. After the activities in the succession (sequence) of submodules are
carried out, the module to the right of the original module is considered.
The main advantage of the hierarchy charts is in the initial planning of a program.
We break down the major parts of a program so we can see what must be done in

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

general. From this point, we can then refine each module into more detailed plans using
flowcharts or pseudocodes (we describe this method as divide and conquer) method.
As an example, write an algorithm and show the hierarchy chart for determining
the number of postage stamps to put on an envelop when you post a letter.
One rule of the thumb is to use one stamp for every five(5) sheets of paper or
fraction thereof. Hence, suppose a friend asks you to determine the number of stamps to
place on an envelope, the following algorithm will be used to accomplish the task.

Input: 1. Request the number of sheets of paper; all it sheets

Processing: 2. Divide sheet by 5


3. Round the quotient up to the next highest whole number; call it stamps.

Output: 4. Reply with the number of stamps.

From this simple algorithm above, the number of sheets are sent in as input, processes
the data and produces the number of stamps needed as output.
As earlier discussed, testing the logic: We can test the algorithm for a letter with
16v sheets of paper:
1. Request the number of sheets of paper; sheet = 16
2. Divide 16 by 5 gives 3.2
3. Rounding 3.2 up to 4 gives stamps = 4
4. Reply with the answer, 4 stamps:

In Hierarchy Chart:
Postage Stamp
Program

Calculate
Read Stamps Display
Sheets Stamps

Set Stamps = Round Stamps


Sheets/5 up to next
whole number

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Flowchart
A flowchart is a step-by-step diagrammatic representation of the logic paths to
solve a problem. It is a graphical way of depicting a problem in terms of inputs, outputs
and processes. A flowchart consists of special geometric symbols connected by arrows,
within each symbol is a phrase representing the activity at that step with the shape of the
symbol indicating the type of operation that is to occur.
Flowcharts as advantageous because it provides a pictorial representation of the task
which makes the logic easier to follow while it’s disadvantageous when we have large
programs. The may continue for many pages which may make them difficult to follow
and modify.

Symbols

Flowline: The flowline symbol is used for indicating the direction of flow.
All lines of an algorithm represented in a flowchart must have an arrow to indicate it’s
direction.

Input/Output: Parallelogram shapes are used for input and output operations
such as reading and printing.

Terminal: This symbol is used to represent the beginning (start) and end
(stop) of a task.

Processing: The symbol is used to indicate or show any set of processing


operation. Operations such as arithmetic and data-manipulation activities are listed
inside the symbol.

On Page Connector: The connector or on page connector is used to join


different flowlines.

Off Page Connector: This symbol represents a break in the path of flowcharts
which is too large to fit on a single page. It marks where an algorithm ends on
the first page and where it continues on the second page.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Decision Symbol: The decision maker symbol is used for many logic or
comparison operations. Unlike the input/ouput and processing symbols which
have one entry and one exit flowline, the decision symbol has one entry and two(2) exit
paths. The path chosen depends on whatever the answer to a question is yes or no.

Annotation Symbol: This symbol is used to provide additional information


about another flowchart symbol.

Subroutine Predefined Symbol: The symbol is used to indicate a sequence


of actions that perform a specific task embedded withing a larger process. The sequence
of actions can be described in a more detailed piece on a sequence flowchart.

Sort Symbol: Indicates a step that organizes a list of items into a sequence of sets
based on some predefined criteria.

Merge Symbol: This symbol is used where 2 or more sub-lists or sub-processes


become one.

Manual Loop Symbol: The symbol indicates a sequence of commands that will
continue to repeat until when stopped manually.

Database Symbol: The symbol indicates a list of information with a standard


structure that allows for searching and sorting.

Manual Input Symbol: It is used to represent a step where a user is prompted to


enter a particular information manually.

Internal Input Symbol: This is used in software design flowcharts to show that
information was stored in memory in a program.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Example On Stamp:

Start

Read
Sheets

Set Stamps =
Sheets/5

Round Stamps up to
next whole number

Display
Stamps

Stop

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Pseudocodes: Pseudocode is an abbreviated version of actual computer code, it is


neither an algorithm nor a program. It is an abstract form of a program. In pseudocode,
the geometric symbols used in flowchart are replaced by English-like statement that
outlines the process. All pseudocode look more like computer code than does a
flowchart. It allows programmers focus on the steps required to solve a problem neither
than on how to use the computer language.
For the postage stamps; the pseudocode can be written as:
Read Sheet
Set the number of stamps to sheets/5 (sheets divided by 5)
Round the number of sheets up to the next whole number.
Display the number of stamps.

Similarly, pseudocodes are compact and probably will not extend for as many pages as
flowcharts commonly do especially for large and complex programs. Also programmers
will prefer pseudocodes to flowcharts because the plan looks like the code to be written.
There are basically two(2) types of structures in programming. The sequence
structure and the decision structure. For example in the postage stamp example, each
step was in sequence, that is, we moved from one line to the next without skipping over
any lines (sequence structure). Many problems however in real life require a decision to
determine whether a series of instructions should be executed or not. When the answer
to the question is yes (some lines if instruction will be executed) and when NO another
set will be executed. This structure is called a decision structure for example,

Is
condition
true If Condition is true
Process Process Process step(s) 1
step(s) 2 step(s) 1 Else
Process step(s) 2
EndIf

This presents a pseudocode and flowchart for the decision.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

1. Write an algorithm and draw a flowchart to convert temperature from Fahrenheit (F)
to Celsius (oC)

Step 1: Read temperature in Fahrenheit


2: Calculate temperature with formular C = 5/9 * (F–32)
3: Print temperature in Celsius.

Start

Read in
temp. in F

Begin
Compute temp in
Input temp in OF
C = 5/9 * (F-32) Calculate temp in OC =
5
/9 * (F – 32)
Print C
End .
Read in
temp. in F

End

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

2. Write an algorithm to compute the wages of an employer. Also draw the flowchart
and write out the pseudocode.
Step 1: Input the number of hours and rate per hour
2: Calculate the wages
3: Print out the wages

Start

Input hours

Input rate per


hour

Wages = hours *
rate

Begin
Input hours
Print wage Input rate per hour
Wage = hours * rate per hour
Print pay
Stop

End

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

3. Write an algorithm that shows the flowchart to calculate the simple interest on a loan.
Step 1: Read in the 3 inputs (P, R and T)
2: Calculate the simple interest using (PRT)/100
3: Print Simple Interest

Start

Inputs P, R
and T

Compute Simple
Interest S = P*R*T Begin
100 Input P, R and T
Compute S.I = P*R*T
100
Print S
End
Print S

Stop

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

4. Write an algorithm to compute the volume of a cube.


Step 1: Read in the Length, Width and Height
2: Calculate Volume = length * height * width
3: Print volume.

Start

Get the input for


length* width *
height

Compute Volume = Begin


Lenght * Height * Input Width, Lenght and height
Width Calculate volume = Length * Width * height
Print Volume
End .

Display
volume

End

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

5. Write an algorithm to determine whether a temperature is below freezing point.


Step 1: Input temperature
2: If the temperature is less than 32O, the print below freezing point

Start

Read in
Begin
Temerature Input temperature
If temperature is < 32O
Display “Below freezing point”
End .

Is
Temperature YES
<32O

Print
NO “Below freezing Point”

Stop

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

6. Design an algorithm to determine whether a student passed the exam or not in an


exam of 4 courses using the average grade.
Step 1: Input grades of the four (4) courses using the average grade.
2: Calculate the average grade = Sum of the scores / 4
3: If average grade is less than 60, print “Fail” else print “Pass”

Start

Input M1, M2,


Begin
M3 & M4 Input M1, M2, M3, and M4
Compute Average Grade =
(M1 + M2 + M3 + M4) / 4
Store as Grade
Grade = (M1 + M2 + M3 + M4) If Grade > 60 then
4 Display Pass
Else
Display Pass
EndIf
End .

No Is Grade YES
> 60

Print Print
“Fail” “Pass”

End

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

7. Design an algorithm to compute the sum if five(5) numbers


Step 1: Set sum and counter to 0
2: Input number
3: Add number to sum and assign to sum and increment counter by 1
4: If counter < 5 goto 2 else print sum

Start

Sum = 0
Counter = 0

Enter
Number Start
Intialize Sum = 0 and Counter = 0
While Counter < 5
Enter number
Add number to Sum
Sum = sum + number Increment the Counter
Counter = Counter + 1 Display Sum
End .

Is
NO YES
Counter
<5

Print Sum

Stop

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Assignment
8. Auditors’s forum has launched a promotion for it’s credit card customers. According
to the promotion, the customers will receive a gift voucher worth $500 with their
monthly bill if they spend $15,000 more than their last month spending and their last
month spending bill is not less than $10,000
Step 1: Input current and last month spending
2: if last month spending is not less than $10,000 and current month spending
is greater than $15,000 then award gift voucher.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Bug Description of Visual Basic


Visual Basic is a high level programming language which evolved from the earlier
DOS version called BASIC (Beginner All-Purpose Symbolic Instruction Code).
Different Software companies produced different version of BASIC such as Microsoft
QBASIC, QUICKBASIC, GWBASIC etc. Visual Basic a Visual and Event driven
programming language which is the new divergence from the old BASIC.
In BASIC, programming is done in a text only environment and program is
executed sequentially while in VB, programming is done in a graphical environment and
because users may click on an object randomly, each object (control) has to be
programmed independently to be able to respond to those actions (events). Examples of
event includes clicking a command button, entering text in a text box, selecting an item
in a listbox etc. VB is a programming language made up of many subprograms each
with it own program code which can be executed independently and at the same time
can be linked together on way or another

Invoking Visual Basic 6.0


To invoke Visual Basic 6.0 click the start button on the task bar, point to all programs,
point to Microsoft Visual Basic 6.0 and click on it. On display, the main part of the
window is a tabbed dialog box with three(3) tabs (New, Existing and Recent); the
number of project icons showing at either three(3) (with the working model and learning
editions) or thirteen(13)(with the professional and Enterprise Editions).
Double-Click on the Standard EXE icon (EXE → Executable Program) to bring
the initial VB Screen [It should be noted that the screen varies slightly to one another
based ob their versions].
The VB Environment Consists of
- The main window.
- A blank form used by users to design their application’s interface.
- The project window which displays the properties of various controls and objects that
are created in the user’s application.
- The toolbox which consists of all controls essential for developing a VB application.
- The form layout window.

The main window consists of the title bar (Which indicates the project name, the current
VB operating mode and the current form), menu bar (contain drop-down, menus from
which user control the operation of the Visual Basic environment) and the title bar
[contains shortcuts (in form of buttons) to some of the menu options].

The form window is central important to developing any VB application. It is where


users draw their applications.
The form layout window shows where (upon program execution) users window will be
displayed relative to user’s screen.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

The project window displays a list of all forms and modules making up a user
application. The user can also obtain a view of the form or code windows (window
containing the actual basic coding) from the project window.
The properties window is used to display the initial property and also for objects
(controls) that are created in a user’s application and also used to change how these
objects look like. Two(2) views are available, Alphabetic and Categorized.
The toolbox consists of all the controls essential for developing a VB application.
These controls are represented in form of icons that ca be dragged or drawn on a form to
perform certain task according to the events associated with them. Some of these
controls are:

i. Textbox; This control is used to receive input form users as well as to display the
output. It can handle string (text) and numeric data but not images. String in a
textbox can be converted to a numeric data by using the function Val(text).
ii. Label: The label is a very useful control for VB as it is not only used to provide
instructions and guides to the users, it can also be used to display outputs.
iii. Command Button: This control is used to execute commands, a click on a
command button initiates an action. The most common event associated with the
command button is the click event.
iv. Picture box: This is one of the controls that are used to handle graphics.
Pictures(s) can be loaded at the design phase or at runtime using the load picture
method. Image here is not resizable.
v. Imagebox: The Image box has a function almost identical to the picture box with
one major difference, the image in an image box is stretchable (resizable).
vi. List box: The list box is to present a list of items where the users can click and
select the items form the list. To add items to the list, we can use the AddItem
method.
vii. Checkbox: The checkbox control allows the users to select or deselect an option.
When the checkbox is checked, its value is set to 1 and when it is unchecked, the
value is set to 0.
viii. OptionBox: This control allows a user select one of the choices available. Two or
more option boxes must work together because as one of the option boxes is
selected, the other option boxes will be unselected, that is, one option box can be
selected at one time.
ix. Drive List Box: The drive list box is used to display list of drive available on a
user’s computer. When a users places this control into the form and run the
program, the user will be able to select different drives from the computer.
x. Directory Listbox: The control is used to display the list of directories or folders
in a selected drive. When a user places this control into the form and run the
program, you (the user) will be able to select different directories from a selected
drive on the computer.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

xi. File Listbox: The File Listbox is used to display the list of files in a selected
directory or folder, with this control, a user will be able to list the files available
in a selected directory.

Steps in developing applications:


There are three(3) primary steps involved in building or creating a Visual Basic program
are as follows:
i. Create the interface, that is generate, position and size the object.
ii. Set properties; that is, set the relevant properties form the objects.
iii. Write/attach code to controls, that is write the codes that executes when the events
occurs. Codes consists of statements that carryout tasks.

As mentioned in (i), the user interface is drawn on the form window.


Two ways to place controls on a form:
- Double-Click on the tool in the toolbox and it is created with default size on the form
which can the be resized.
- Click the tool in the toolbox then move the mouse pointer to the form window. The
cursor changes to a crosshair, place the crosshair at the upper left corner of where you
ant the control to be drawn, press the left mouse button and hold it down while dragging
the cursor towards the lower right corner. When the mouse button is being released, the
control is drawn.

To move a control a user has drawn, click on the object and hold down the left mouse
button on the form window and drag it to the new location. Release the mouse button.
To resize a control, click the object so that sizing handles appear. Use these handles to
resize the object.
A statement to be executed when an event is to occur are written in a block of codes
called an event procedure. The structure of any event procedure is:

Private Sub ObjectName_event()


Statement(s)
End Sub

Private: The world Private means that the event procedure cannot be invoked by an
event from another form.
Sub: The word Sub signals the beginning of the event procedure.
ObjectName_event(): This part identifies the object and the event occuring in the object
(control).
Statements(s): These are the statements to be executed.
End Sub: This signals the termination of an event procedure.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Properties of an object are changed while a program is running in the statements of the
form:
objectName.property = setting

Where objectName is the name of the form or controls.


Property is one of the properties of the object.
Setting is a valid setting for the object.
This type of statement are called Assignment Statements
Examples of such statements are:

txtWale.Font.Bold = True
txtWale.Text = “Adewale Ajibola”
txtWale.Font.Size = 12

It should however be noted that the form is the default object (control) in Visual Basic
code, hence, Code such as:

Form1.property = Setting
can be written as
property = Setting

A Visual Basic program can be ended or stopped by clicking on the End icon or by
pressinf Alt+F4. A more elegant or professional way is to create a Command button and
name it say CmdQuit and set QUIT or END as it ‘s caption and

Private Sub cmdQuit_Click()


End
End Sub

as it’s event procedure.


At the design time, color are selected from a palette. At run time, eight most common
colors can be assigned with the color constants vbBlack, vbRed, vbGreen, vbYellow,
vbCyan, vbWhite and vbMagenta

E.g
picWale.BackColor = vbGreen
gives a pictureBox with the name picWale a green background.

The code window has many word processor features. The operation to copy, paste, find,
undo and redo can be carried out with the 6 th and 11th icons of the toolbar while some
others can be initiated from the Edit menu.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

NUMBERS
Much of the data processed by computers consists of numbers in computerese, numbers
are referred to as numeric constants. The way to show a number on the screen in Visual
Basic is to display it in a pictureBox. Hence, if n is a number, then the instruction
picBox.Print n
display the number in the picture box
If the picBox.Print instruction is followed by a combination of numeric and arithmetic
operations, it carries out the operations and display the result. Print is a reserved word
and the print operation is called a method. Another important method is Cls, the
statement picBox.Cls erases all text and graphics from the picture box picBox.
As an example, a picture box and a command button both placed on the Form
with picResult, cmdCompute as their object names and Compute as the cpation
property for the command button. Run the following

Private Sub cmdCompute_Click()


picResults.Print 3+2
picResults.Print 3-2
picResults.Print 3*2
picResults.Print 3/2
picResults.Print 3^2
picResults.Print 2*(3+4)
picResults.Print 1.2*10^34
picResults.Print 10^-20
picResults.Print 3.3*10^21
End Sub

Semicolons can be used to display several numbers with one method, that is m, n and r
are numbers, a line of the form picBox.Print m;n;r displays the three(3) numbers one
after another. Hence the statements above can be written as:

Private Sub cmdCompute_Click()


picResult.Print 3+2; 3-2; 3*2; 3^2; 2*(3+4); 10^-20; 10^21; 3.3*10^21
End Sub

Numbers must not contain commas, dollar sign or percent signs. Mixed numbers like
81/2 are not allowed. Parenthesis should be used not necessary to clarify the meaning of
an expression but when there’s no parenthesis, the arithmetic operations are performed
in the following order:
i) Exponentiations ii) Multiplication and divisions iii) Additions and Subtraction
while in the event of ties, the leftmost operation is carried out.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Error Types
In Visual Basic, errors (exceptions) fall into one of the three(3) categories
Syntax errors, Run time errors and Logic errors.

i) Syntax Error: Syntax errors are errors that appear while writing code. Grammatical
errors such as misspelling or incorrect puntuations falls under this category of error.
Visual Basic checks our code as we type it in the code editor window and alert us when
we make a mistake. Syntax error are the most common type of errors which can be fixed
easily in the coding environment as they occur.
However, the option Explicit Statement is one means of avoiding syntax errors. It forces
the programmer to declare in advance the variables to be used in the application
therefore when those variables are used in the code, any typographical error are caught
immediately and can be fixed.
E.g picWale.Primt 3 (Mis-spelling of Keyword)
9W = 5 (9W is not a valid variable name)

ii) Run-time error: Errors detected while running a program are called run-time errors.
Although some run-times are due improper syntax, others result from the inability of the
computer ti carry out the intended task. For example, you might correctly write of code
to open a file but if the file is corrupt, the application will not carry out the open function
and stop running. Also if the value of numVar is 0 then the statement
numVarInv = 1/numVAr
will interrupt the program with run-time error “Division by zero”.
The dialog box generated by a run time error state the type of error and has a row
of four(4) command Buttons captioned Continue, End, Bug and Help. If you click on
the Debug Button, VB will highlighting yellow the line of code that caused the error. It
should be noted that when run time occur, the program is said to be in the Break Mode.

Iii) Logic error: Logic errors are those that appear once the application is in use. They
are most often unwanted or unexpected results in response to user actions, that is, the
application is not performing the way it was intended. As an example, the line
owe = FirstNum + SecondNum / 2
is syntactically correct but the absence of parenthesis in the First line (statement) are
responsible for any incorrect value being generated.
Logic errors are generally the hardest type of error to fix since it is not always
clear where they originate.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Strings
Two primary type of data can be processed by Visual Basic; Numbers & Strings.
Sentences, phrases, names, telephone numbers, address are examples of strings. A string
constant is a sequence of characters. It is treated as a single item. Strings can be assigned
names with assignment statements, can be displayed with Print methods and can be
combined by an operation called concatenation (&)

Today = “10/03/2014”
picWale.Print “hello”
picWale.Print Today
quote1 = “The game is not over ”
quote2 = “until it is over”
picWale.Print quote1 & quote2

String constants used in Assignment or picBox.Print statements must be surrounded by


quotation marks but string variables are never surrounded by quotation marks when used
in Print statement.

VARIABLES: Variables are used to hold information needed by your application.


A variable is a storage location paired with an associated name (identifier) which
contains some known or unknown information called value. The variable name is the
usual way to reference the stored value, this seperation of name and content allows the
name to be used independently of the exact information it represents. Variables can
represent numeric values, characters, memory address etc. The identifier can be bound to
a value during the course of the program execution e.g It can be employed in the
repetitive process (iteration). This means that while a variable’s name, type and location
often remain fixed, the stored data in the location may be changed during the course of
program execution.
Variables play an important role in programming as it enables programmers to
write flexible programs and rather than entering data directly into a program, a
programmer can use variable to represent the data.
While naming variables, the following rules must be strictly adhered to.
- The name must be not be more than 255 characters.
- No spacing is allowed or character used to specify a data type.
- It must begin with a letter of the alphabet.
- Must not be a reserved word.
- Period is not permitted.

Visual Basic does not distinguish between upper and lower case letters but as a
convention, we write variable names in lower letters except th efirst letters of additional
words e.g kwasuStudent, numberOfCars etc.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

In Visual Basic, one need to declare the variables before using them by assigning names
and data types. There are three ways of declaring variables in Visual Basic.

- Default -Implicit -Explicit

If a variable is not implicitly or explicitly declared, they are assigned the variant type by
default. The variant data type is a special type of declaration use in VB that can contain
numeric, string or date data.
In Implicit declaration, a variable uses a corresponding suffix to specify the data type e.g

textValue$ = “This us a String” ‘ - creates a string variables


amount% = 300 ‘ - creates an integer variables

From the data type table as show below

Data Type Suffix


Boolean None
Integer %
Long (Integer) &
Single (Floating) !
Double (Floating) #
Currency @
Date None
Object None
String $
Variant None

Explicit declaration in VB takes place in the general section of the codes windows using
the Dim Statement with the syntax

Dim variableName As DataType e.g


Dim password As String
Dim doDate As Date
Dim yourName As String
Dim secondNum As Integer

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

One can also combine them in one line seperating each variable with a comma e.g
Dim password As String; doDate As Date. ‘etc
In string declaration, there are two(2) possible formats, one for the variable length string
and the other for the fixed-length string.
For variable length string, use the same format as above while in fixed-length, use
Dim variableName As String*n
where n defines the number of characters the string can hold e.g
Dim vyourName as String*20
means yourName can hold not more than 20 characters.

Dim = Dimension = Declare in memory

Variables must be of a certain/particular data type. When a variable is declared, a data


type is supplied for it which determines the kind of data they can store. The fundamental
data type in VB are Integer, Long, Single, Double, String, Currency, Byte and Boolean.
In VB each data type has limit to the kind of information and minimum and maximum
values it can hold.

Numeric:
Byte - Stores integer values in the range of 0-255
Integer - Stores integer values in the range – 32,768 and +32,768.
Long-Stores integer values in the range -2,147,483 and +2,147,483,468
Single - Stores floating values in the range -3.4x10-38 and +3.4x10-38
Double -Stores large floating point values which exceeds single data type.
Currency – Stores monetary values. It support 4 digits to the right of the decimal point
and 15 digits to the left.
String – Stores alphanumeric values. A variable length-String can store approximately 4
billion characters.
Date: Stores date and time.
Boolean: This data type hold either a True or False value. They are internally stored as
1(True) or 0(False)
Variant: Variant is a datatype that stores any/all types of data. It is the default VB data
type. If a variable is declared in VB without a data type, it is assigned a default data
type.

Reserved Words
A word is said to be a reserved word (Keyword) in VB or any programming
langauge if it has a specific function or command in the language and cannot be used as
the name of a variable, constant, function or procedure. In VB, a variable cannot be
named Print because it is a Keyword in VB. Other examples include False, Next, Sub,
While, If…..Else, Until etc.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Concentration
Two(2) Strings can be combined to form a row string consisting of strings joined
together. The joining operation is called concatenation is represented by an
ampersand(&) e.g
“good” & “bye” ‘ will result in “goodbye”
“mother” & “hood” ‘will result in “motherhood”

A combination of strings and ampersand that can be evaluated to form a string is called a
string concatenation. Concatenation operation of strings can also represented by a
plus(+) but in order to eliminate ambiguity and self-documention, plus sign may be
restricted to operations on numbers.

Operators in VB
In order to compute inputs from users and generate results, we need to use various types
of operators. The operators mostly used in are the arithmetic, relational (comparison)
and logical operators.
- Arithmetic Operators: Except for + and -, the symbols for the operation are different
from normal mathematical operators.

^ → Exponentiation + → Additions
* → Multiplication - → Subtraction
/ → Division () → Parenthesis → Changing Precedence
Mod → Modulus (Returns the remainder of an integer division. i,e 15 Mod 2 = 1)
\ → Integer Division (Discards decimal places, e.g 19/4 = 4)
& → String Concatenation

- Relational Operators: The relational or comparison operators are usually used in


control structures with result as a boolean

> → Greater than = → Equal to


< → Less than <> → Not equal to
>= → Greater than or equal to
<= → Less than or equal to

Logical Operators: In addition to condition operators, there are a few logical operators
which offer added power to the VB programs.
AND → Operation is true only if both operator are true.
OR → Operation is true if either (any) of the 2 operands is true.
NOT → The Not operator simply negates an operand
XOR → One side or the other must be true but not both to have true value

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Explicit Declaration
Declaring a variable tells Visual Basic to reverse space in memory, though it isn’t a must
a variable be declared before using it. When VB encounters a new variable, it assigns the
default variable and value variant (Variant). This is easier and convenient for the user. It
is advisable to declare variables explicitly.
Ir may be convenient as earlier stated to declare variable implicitly or with the
variant data type but it can lead to error that ma not be recognized at run-time. To avoid
this errors, we can declare variables by adding option Explicit to the general declaration
section of the form. This forces the users to declare all variables to be used in the
program. The option Explicit statement checks in the module for usage of any
undeclared variables and reports an error to user. The user upon sighting the reported
error can this rectify the error.

Scope of variables
A variable can be scoped to a procedure-level (local) or module level variable
depending on how it is declared. The scope of variable, procedure or object determines
which part of the code in an application are aware if the variable’s existence.
A variable declared in the general declaration section of form is available to all
procedures in the program. Local variables are recognized only in the procedure in
which they are declared. They use the Dim and Static keywords. If a variable is to be
made available to all of the procedure within the same module, or to all the procedures
in an application, the variable should be declared with a broader scope.
Local variables are the ones declared inside a procedure, the variable is only
available to the code inside the procedure and can be declared using the Dim statement.
Local variable exist as long as the procedure in which they are declared is executing.
Once a procedure is executed, the values of it’s local variables are lost and the memory
used by these variables are freed. All variables declared with keyword Dim exist only as
long as the procedure is being executed.
Static variables are not re-initialized each time Visual Basic is being invoked, and
this refrains/preserves value even when the procedure ends.
Variables have a lifetime with respect to their scope; The value in a module or public
variables are preserved for lifetime of an application whereas local variables declared
with Dim exist while the procedure in which they are declared is still being executed.
However, the value of a local variable can be reserved using the static keyword. Hence,
to make all variables in a procedure static, the static keyword is placed at the beginning
of the procedure heading.
In the module level variable, variables are available to all procedures in the
module. They are declared using the Public or the private keyword. If a declaration
using a Private or Dim statement is made at the declaration section of a module, a
module, you are creating a Private module-level variable, such variable are usable only
from within the module they belong to can can’t be accessed from the outside. These

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

variables are useful for sharing data among procedures in the same module. A Public
module-level variable can be accessed by all procedures in the module to share data and
that also can be accessed from outside the module. It is however more appropriate to
describe such a variable as a property.

Control Structure
A control structure is a block of programming that analyses variables and chooses a
direction in which to go based on some parameters. It is a basic decision making process
in Computing. They are used to control the flow of programs execution. Visual Basic
supports the selective and reflective structures.

Selective
- If...Then selective structure
The If...Then selection structure performs an indicated action only when
the condition is True; otherwise the action is skipped

If <condition> Then
Statement(s)
End If
Is average Yes
grade > 50 Display Passed

No

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

If...Then...Else...Selective Structure
The If...Then...Else selective structure allows the programmer to specify that a
different action is to be performed when the condition is True than when the condition is
False.

If <condition> Then
Statement(s)
Else
Statement(s)
End If
No Is average Yes
grade > 50

Display Failed Display Passed

Nested If… Then… Else Selective Structure.


This structure test for multiple cases by placing If… Then… Else selective
structures inside If… Then… Else structures. It can be used with any of the following:
If <Condition 1> Then If <Condition 1> Then
Statement(s) Statement(s)
Else If <Condition 2> Then Else
Statement(s) If <Condition 2> Then
Else If <Condition 3> Then Statement(s)
Statement(s) Else
Else If <Condition 3> Then
Statement(s) Statement(s)
End If Else
Statement(s)
End If
End If
End If

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Let’s assume you have to find grade for an average score using the nested If and display
in a textbox.

If average > 75 Then If average > 75 Then


txtGrade.Text = “A” txtGrade.Text = “A”
Else If average > 65 Then End If
txtGrade.Text = “B” If average > 50 Then
Else If average > 55 Then txtGrade.Text = “Pass”
txtGrade.Text = “C” Else
Else If average > 45 Then txtGrade.Text = “Fail”
txtGrade.Text = “D” Else If
Else
txtGrade.Text = “F”
End If

Select… Case Selection Structure


The select case structure is an alternative to the If… Then… Else If for
selectively executing a single block of statement for among multiple block of
statements. Select case is more convenient to use than the If… Else… End If

Syntax: Select Case Index


Case 0
Statement(s)
Case 1
Statement(s)
Case Else
Statement(s)
End Select

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

For the previous example on average grade

Dim average as Integer


average = Val(txtAverage.Text)
Select Case average
Case 100 To 75
txtGrade.Text = “A”
Case 74 To 65
txtGrade.Text = “B”
Case 64 To 55
txtGrade.Text = “C”
Case 54 To 45
txtGrade.Text = “D”
Case 44 To 0
txtGrade.Text = “F”
Case Else
txtGrade.Text = “Invalid Average Mark”
MsgBox “Invalid Average Marks”
End Select

Repetitive Structure (Loop)


A loop is a programming structure that repeats a sequence of instructions until a
specific condition is met. Loops are supported in all modern programming languages
though implementations and syntax may differ. In Visual Basic like other languages,
loops structures allow you to run one or more lines of codes repetitively. Statement in a
loop structure can be repeated until a condition is True, until a condition is False, a
specific number of times or for each elements in a collection.
There are basically two types(2) of loop; the pretest and the posttest loops.
In a pretest loop, we test to see whether or not to continue before executing the body of
the loop, that is, in a pretest loop, a logical condition is checked before each repetition
to determine if the loop should continue or be terminated. The effect of this is that we
might not execute the body of the loop at all.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Condition
In this pretest loop, the loop’s condition
(Boolean expression) is tested before the
loop is executed. If Condition is True,
True then the loop is executed; if the condition
is False, the loop body is not execute.
Code Block Therefore, as earlier said it is possible that
these loops may not be executed at all. A
pretest loop is called an entrance
controlled loop.

As we have a structure that tests the continuation condition at the top, we also have one
that tests it at the bottom. This structure is called a Post-Test loop. This structure also
called the exit controlled loop will always have the body of the loop executed at least
once. This distinguishes it from the pretest loop. The post-test loop save time that may
be wasted if testing the condition before entering the loop

Here, the test condition for the execution


Code Block of the repetition statement is evaluated
after executing each run of he loop
termination

True Condition

False

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

There are basically 3 parts of a loop;


i. Initialization: commands / setup of the loop (setting counters to initial value etc).
ii. Terminating Condition: A logical condition that is checked to terminate the loop.
iii. Loop Body

Example:

Initialization: Counter set to 0


Counter = 0; Termination: Counter < 5
Body:
Action: Print
Update: Increment Counter by 1

Counter < 5

False
True
Print (?)
Counter++

Types
Do… While… Loop Statement: A Do… While… Loop is used to execute statements
until condition is met.
Here the variable number is initially set to 1
Dim number As Integer
number = 1 and then the Do... While… Loop Starts. First
Do While number <= 100 the condition tested. If condition is True, then
number = number + 1 the statements are executed. When it get to the
Loop end of the loop, it goes back to the Do and
tests condition again. If the condition is False
on the First pass, the statements are never
executed.

Do… Loop.. While Statement: The Do… Loop… While statement first execute the
statements and then test the condition after each execution.

Downloaded by ayodeji tobiloba ([email protected])


lOMoARcPSD|55615542

Dim number As Long The program executes the statement between


number = 0 Do and Loop While structure in any case.
Do Then it determines whether the counter is less
number = number + 1 than 201. If so, the program again executes the
Loop While number < 201 statements between the Do and Loop While
else exits the loop.

Do… Until… Loop Statement: This structure test a condition for Falsity. Statements in
the body of this structure are executed repeatedly as long as the loop-continuation test
evaluate False.

Dim number As Long


number = 0 This will display numbers 1 to 1000 as
Do Until number > 1000 soon as the Command button is clicked
number = number + 1
Print number
Loop

Downloaded by ayodeji tobiloba ([email protected])

You might also like