Cos 102 Problem Solving Techniques
Cos 102 Problem Solving Techniques
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
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.
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
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.
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.
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.
Sort Symbol: Indicates a step that organizes a list of items into a sequence of sets
based on some predefined criteria.
Manual Loop Symbol: The symbol indicates a sequence of commands that will
continue to repeat until when stopped manually.
Internal Input Symbol: This is used in software design flowcharts to show that
information was stored in memory in a program.
Example On Stamp:
Start
Read
Sheets
Set Stamps =
Sheets/5
Round Stamps up to
next whole number
Display
Stamps
Stop
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
1. Write an algorithm and draw a flowchart to convert temperature from Fahrenheit (F)
to Celsius (oC)
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
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
Wages = hours *
rate
Begin
Input hours
Print wage Input rate per hour
Wage = hours * rate per hour
Print pay
Stop
End
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
Start
Display
volume
End
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
Start
No Is Grade YES
> 60
Print Print
“Fail” “Pass”
End
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
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.
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 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.
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.
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: 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.
Properties of an object are changed while a program is running in the statements of the
form:
objectName.property = setting
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
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.
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
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:
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.
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.
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
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.
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.
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
Explicit declaration in VB takes place in the general section of the codes windows using
the Dim Statement with the syntax
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.
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.
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
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
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
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
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
Let’s assume you have to find grade for an average score using the nested If and display
in a textbox.
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
True Condition
False
Example:
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.
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.