CSC 112 Course Final New 2023
CSC 112 Course Final New 2023
Problem Solving
Solving problems is the core of computer science. Programmers must first understand how a
human solves a problem, then understand how to translate this "algorithm" into something a
computer can do, and finally how to "write" the specific syntax (required by a computer) to get
the job done. It is sometimes the case that a machine will solve a problem in a completely
different way than a human.
Computer Programmers are problem solvers. In order to solve a problem on a computer you
must:
Information Representation
A computer, at heart, is really dumb. It can only really know about a few things... numbers,
characters, booleans, and lists (called arrays) of these items (See Data Types). Everything else
must be "approximated" by combinations of these data types.
A good programmer will "encode" all the "facts" necessary to represent a problem in variables
(See Variables). Further, there are "good ways" and "bad ways" to encode information. Good
ways allow the computer to easily "compute" new information.
Algorithm
An algorithm is a set of specific steps to solve a problem. Think of it this way: if you were to tell
your 3 year old niece to play your favorite song on the piano (assuming your niece has never
played a piano), you would have to tell her where the piano was, and how to sit on the bench,
and how to open the cover, and which keys to press, and which order to press them in, etc, etc,
etc.
Page 1 of 77
The core of what good programmers do is being able to define the steps necessary to accomplish
a goal. Unfortunately, a computer, only knows a very restricted and limited set of possible steps.
For example a computer can add two numbers. But if you want to find the average of two
numbers, this is beyond the basic capabilities of a computer. To find the average, you must:
1. First: Add the two numbers and save this result in a variable
2. Then: Divide this new number with number two, and save this result in a variable.
3. Finally: provide this number to the rest of the program (or print it for the user).
Computer scientists like to use the fancy word "Encapsulation" to show how smart we are. This
is just a term for things we do as humans every day. It is combined with another fancy term:
"Abstraction".
Abstraction is the idea of "ignoring the details". For example, a forest is really a vastly complex
ecosystem containing trees, animals, water paths, etc, etc, etc. But to a computer scientist (and to
a normal person), its just "a forest".
For example, if your professor needs a cup of coffee, and asks you the single item: "Get me a cup
of coffee", he has used both encapsulation and abstraction. The number of steps required to
actually get the coffee are enumerable. Including, getting up, walking down the hall, getting in
your car, driving to a coffee stand, paying for the coffee, etc, etc, etc. Further, the idea of what a
cup of coffee is, is abstract. Do you bring a mug of coffee, or a Styrofoam cup? Is it caffeinated
or not? Is it freshly brewed or from concentrate?
All of this information is TOO MUCH and we would quickly be unable to function if we had to
remember all of these details. Thus we "abstract away" the details and only remember the few
important items.
This brings us to the idea of "Complexity Hiding". Complexity hiding is the idea that most of the
times details don't matter. In a computer program, as simple an idea as drawing a square on the
screen involves hundreds (if not thousands) of (low level) computer instructions. Again, a person
couldn't possible create interesting programs if every time they wanted to do something, they had
to re-write (correctly) every one of those instructions. By "encapsulating" what is meant by
"draw square" and "reusing" this operation over and over again, we make programming tractable.
Encapsulation
The idea behind encapsulation is to store the information necessary to a particular idea in a set of
variables associated with a single "object". We then create functions to manipulate this object,
regardless of what the actual data is. From that point on, we treat the idea from a "high level"
rather than worry about all the parts (data) and actions (functions) necessary to represent the
object in a computer.
Page 2 of 77
Problem – a state of desire for reaching a definite goal from a present condition
Solution – the management of a problem in a way that successfully meets the goals set for
treating it
One important call-out is the importance of having a goal. As defined above, the solution may
not completely solve problem, but it does meet the goals you establish for treating it–you may
not be able to completely resolve the problem (end world hunger), but you can have a goal to
help it (reduce the number of starving children by 10%).
Moreover, it is useful to distinguish between the three words "method", "answer" and "solution".
By "method" we mean the means used to get an answer. This will generally involve one or more
Problem Solving Strategies. On the other hand, we use "answer" to mean a number, quantity or
some other entity that the problem is asking for. Finally, a "solution" is the whole process of
solving a problem, including the method of obtaining an answer and the answer itself.
Fig A
However this chart as is a little misleading. Not all problems follow these steps linearly,
especially for very challenging problems. Instead, you’ll likely move back and forth between the
steps as you continue to work on the problem, as shown below:
Page 3 of 77
Fig B
Let’s explore of these steps in more detail, understanding what it is and the inputs and outputs of
each phase.
2. Brainstorm Ideas
What are some ways to solve the problem? The goal is to create a list of possible solutions to
choose from. The harder the problem, the more solutions you may need.
Input: a goal; research of the problem and possible solutions; imagination.
Output: pick-list of possible solutions that would achieve the stated goal.
3. Decide on a Solution
What are you going to do? The ideal solution is effective (it will meet the goal), efficient (is
affordable), and has the fewest side effects (limited consequences from implementation).
What are you doing? The implementation of a solution requires planning and execution. It’s
often iterative, where the focus should be on short implementation cycles with testing and
feedback, not trying to get it “perfect” the first time.
What did you do? To know you successfully solved the problem, it’s important to review what
worked, what didn’t and what impact the solution had. It also helps you improve long-term
problem solving skills and keeps you from re-inventing the wheel.
Page 4 of 77
Improving Problem Solving Skills With The Use Of Computer
Using the computer for problem solving involves the sequential process of analyzing information
related to a given situation and generating appropriate response options.
Once you understand the five steps of problem solving, you can build your skill level in each
one. Knowing the different problem solving steps allows you to work on your weak areas, or
team-up with someone who’s strengths complement yours.
Problem Solving with the use of computer can be achieved using four basic stages as stated by
Pólya in 1945.
Although we have listed the Four Stages of Problem Solving in order, for difficult problems it
may not be possible to simply move through them consecutively to produce an answer. In fact
the diagram below is much more like what happens in practice.
Figure C
There is no chance of being able to solve a problem unless you first understand it. This process
requires not only knowing what you have to find but also the key pieces of information that
somehow need to be put together to obtain the answer.
It will almost always be necessary to read a problem several times, both at the start and when
working on it. During the solution process, you find that they have to look back at the original
question from time to time to make sure that they are on the right track.
Pólya’s second stage of finding a strategy tends to suggest that it is a fairly simple matter to
think of an appropriate strategy. This exploratory phase will also help to understand the problem
better and may make them aware of some piece of information that they had neglected after the
first reading.
Having explored the problem and decided on a plan of attack, the third problem-solving step,
solve the problem, can be taken. Hopefully now the problem will be solved and an answer
obtained. During this phase it is important for us to keep a track of what is being done. This is
useful to show others what they have done and it is also helpful in finding errors should the right
answer not be found.
At this point, it is worth getting into the habit of looking back over what have being done. There
are several good reasons for this. First of all it is good practice to check the work and make sure
Page 5 of 77
that there are no errors. Second, it is vital to make sure that the answer obtained is in fact the
answer to the problem and not answer to assumed problem. Third, in looking back and thinking a
little more about the problem, another way of solving the problem can be observed. This new
solution may be a nicer solution than the original and may give more insight into what is really
going on. Finally, we may be able to generalize or extend the problem.
Generalising a problem means creating a problem that has the original problem as a special
case. So a problem about checking one lamp holder may be changed into any number of lamp
holder.
Extending a problem is a related idea. Here though, we are looking at a new problem that is
somehow related to the first one.
This brings us to an aspect of problem solving that we haven’t mentioned so far. That is
justification (or proof). Solution to the problem is not complete until the answer can be
justified.
Now in some problems it is hard to find a justification but this step is an important one that
shouldn’t be missed too often. Example is the electronic post UTME DelSU exam that failed in
2015.
Scientific Approach
Another way of looking at the Problem Solving process is what might be called the scientific
approach. We show this in the diagram below.
Figure D
Here the problem is given and initially the idea is to experiment with it or explore it in order to
get some feeling as to how to proceed. After a while it is hoped that the solver is able to make a
guess of what the answer might be. If the guess is true, it might be possible to prove or justify it.
In that case the looking back process sets in and an effort is made to generalise or extend the
problem. In this case you have essentially chosen a new problem and so the whole process starts
over again.
Sometimes, however, the guess is wrong and so a counter-example is found. This is an example
that contradicts the guess. In that case another guess is sought and you have to look for a proof or
another counterexample.
Some problems are too hard so it is necessary to give up. Now you may give up so that you can
take a rest, in which case it is a ‘for now’ giving up. Actually this is a good problem solving
strategy. Often when you give up for a while your subconscious takes over and comes up with a
good idea that you can follow.
Page 6 of 77
That then is a rough overview of what Problem Solving is all about. For simple problems the
four stage Pólya method and the scientific method can be followed through without any
difficulty. Complex problems solving with Computer requires six steps as stated below:
There are at least 6 steps to follow in order to do so. They include the following:
a. Understand the Problem
b. Formulate a Model
c. Develop an Algorithm and/or a flowchart
d. Write the Program
e. Test the Program
f. Evaluate the Solution
In order to come up with a model, we need to fully understand the information available to us.
The Writing stage involves turning the design into a working program. Here, we look at
implementation language whereas earlier stages can be largely language independent. If
simplified versions of the problem have been the focus at the design stage, these can be carried
through to implementation and serve as building blocks, or outline solutions, for a larger
problem, the value of gaining confidence through achieving at least some result should not be
minimized.
In practice, however, techniques such as stepwise refinement are quite difficult to perform if you
do not really know what the solution should be, and students find them hard to apply to small
scale exercises.
The final stage is Review. It is a time of reflection and looking back on the finished product
once the deadline is passed. The aim here is to consolidate the learning process and appreciate
lessons learned. It should also provide a means to build up the store of experience that is applied
in future Design stages.
Suppose a business office requires a program for computing its payroll. There are several people
employed. They work regular hours, and sometimes overtime. The task is to compute pay for
each person as well as compute the total pay disbursed.
Given the problem, we may wish to express our recipe or algorithm for solving the payroll
problem in terms of repeated computations of total pay for several people. The logical modules
involved are easy to see.
Algorithm: PAYROLL
calculate the pay for the individual from the current data,
Page 9 of 77
Figure 1.5 shows a structural diagram for our task. This is a layered diagram showing the
development of the steps to be performed to solve the task. Each box corresponds to some
subtask which must be performed. On each layer, it is read from left to right to determine the
performance order. Proceeding down one layer corresponds to breaking a task up into smaller
component steps -- a refinement of the algorithm. In our example, the payroll task is at the top
and that box represents the entire solution to the problem. On the second layer, we have divided
the problem into two subtasks; processing a single employee's pay in a loop (to be described
below), and printing the total pay disbursed for all employees. The subtask of processing an
individual pay record is then further refined in the next layer. It consists of, first reading data for
the employee, then calculating the pay, updating a cumulative total of pay disbursed, and finally
printing the pay for the employee being processed.
The structural diagram is useful in developing the steps involved in designing the algorithm.
Boxes are refined until the steps within the box are ``do-able''. Our diagram corresponds well
with the algorithm developed above. However, this type of diagram is not very good at
expressing the sequencing of steps in the algorithm. For example, the concept of looping over
many employees is lost in the bottom layer of the diagram. Another diagram, called a flow chart
is useful for showing the control flow of the algorithm, and can be seen in Figure 1.6. Here the
actual flow of control for repetitions is shown explicitly. We first read data since the control flow
requires us to test if there is more data. If the answer is ``yes'' we proceed to the calculation of
pay for an individual, updating of total disbursed pay so far, and printing of the individual pay.
We then read the next set of data and loop back to the test. If there is more data, repeat the
process, otherwise control passes to the printing of total disbursed pay and the program ends.
Page 10 of 77
From this diagram we can write our refined algorithm as shown below. However, one module
may require further attention; the one that calculates pay. Each calculation of pay may involve
arithmetic expressions such as multiplying hours worked by the rate of pay. It may also involve
branching to alternate computations if the hours worked indicate overtime work. Incorporating
these specifics, our algorithm may be written as follows:
Algorithm: PAYROLL
get (first) data, e.g., id, hours worked, rate of pay
while more data (repeat the following)
if hours worked exceeds 40
(then) calculate pay using overtime pay calculation
otherwise calculate pay using regular pay calculation
calculate cumulative pay disbursed so far
print the pay statement for this set of data
get (next) data
print cumulative pay disbursed
The algorithm is the most important part of solving difficult problems. Structural diagrams and
flow charts are tools that make the job of writing the algorithm easier, especially in complex
programs. The final refined algorithm should use the same type of constructs as most
programming languages. Once an algorithm is developed, the job of writing a program in a
computer language is relatively easy. It entails a simple translation of the algorithm steps into the
Page 11 of 77
proper statements for the language. In this text, we will use algorithms to specify how tasks will
be performed. Programs that follow the algorithmic logic will then be easy to implement.
There is a common set of programming constructs provided by most languages, that are useful
for algorithm construction. This includes:
• : test a condition, and specify steps to perform for the case when the condition is satisfied
(True), and (optionally) when the condition is not satisfied (False). This construct was
used in our algorithm as:
• if overtime hours exceed 40
• then calculate pay using overtime pay calculation
otherwise calculate pay using regular pay calculation
• or print data from/to peripheral devices. Reading of data by programs is called data input
and writing by programs is called data output. The following steps were used in our
algorithm:
• read data
write/print data, individual pay, disbursed pay
Languages that include the above types of constructions are for example C, Pascal, and
FORTRAN.
To summarize, program writing requires first formulating the underlying algorithm that will
solve a particular problem. The algorithm is then coded into an algorithmic language by the
programmer, compiled by the compiler, and loaded into memory by the operating system.
Finally, the program is executed by the hardware.
Page 12 of 77
Figure 3
Page 13 of 77
4. A computer can assign a value to a variable or memory location
Computers can assign or change the value of a variable. Some common commands for
assignment are: SET, =, STORE, INITIALIZE, etc. For example:
Set Total to 0
5. A computer can compare two variables and select one of two alternative actions
A computer can compare two variables and use the result of the comparison to select between
one of two alternative actions. Pseudocode uses the keywords: IF,THEN, and ELSE for
decisions.
If the question in the IF clause evaluates to True, the statements in the THEN path are executed.
Otherwise the statements in the ELSE path are executed. Some common commands for making
decisions are: IF/THEN, IF/THEN/ELSE, SWITCH, COMPARE, etc.
For example: IF it is less than 65 degrees F, wear a sweater.
Meaningful names
When designing a solution using Algorithm, a programmer must introduce some unique names
to represent variables or objects.
All names should be meaningful. For example: hoursworked and hourlyrate are more meaningful
than A and B.
1. Sequence
A sequence is a list of instructions to be followed in the order written. Pseudocode shows the
sequence control structure as:
instruction a
instruction b
instruction c
2. Selection
A selection presents a condition and uses the result of the condition to make choice between two
actions. Pseudocode shows the selection control structure as:
3. Repetition
The repetition control structure is a set of instructions to be repeated while a certain condition is
true. Pseudocode shows repetition as:
Each step has attached questionnaire that contain questions that will lead you toward the solution
of the problem. The Guiding-questionnaires to be used with the General Strategy for algorithm
creation are as follows:
Guide 1
1. Do you understand every word used within the problem statement?
2. What computational elements are relevant to the problem?
3. Use your own words to describe the problem. If needed, make a drawing that shows the
situation clearly.
4. Have you solved any similar problem? If so, take advantage of that experience.
5. What data or resources are provided within the statement?
6. What data or results are requested within the statement?
7. Check answers 5 and 6 and decide if they are consistent with your answer in 2.
Guide 2
1. Identify all theoretical (and empirical) concepts related with the problem.
2. Select a structure able to simplify data handling: arrays, records, files, local variables,
global variables, linked lists, etc.
3. Identify the kind of problem(s) according with its (their) structure: sequential, selection,
iterative.
4. Identify available algorithmic elements and select: what you need: well-defined
instructions, already known algorithms, etc.
5. Is it possible to simplify the problem by dividing it into simpler cases and selecting a
different approach for each one? Is it possible eliminate redundant or unnecessary data?
Page 15 of 77
Guide 3
1. Do you know any hand-written way to solve the problem? If so, propose several
examples and solve them "by hand", then attempt to create a generalization. In order to
do that, carefully think on each step performed and watch what actions are common to
every example.
2. Make a list of variable elements, specifying their magnitude and measurement units.
Associate them proper symbols or names but take care of avoid their repetition
3. Which principles or relationships apply to the problem?
4. Write down the selected relationships but using your own variables (symbols or names).
If needed, describe equations with words.
5. Are all variables in use? Are there as many relationships as unknown variables?
6. Are you using all the information available in the problem statement? If not, select just
the important.
Guide 4
Guide 5
1. Manually compute the result (i.e. perform a hand-trace.) If needed, draw plots that
describe the behavior of the variables.
2. Follow strictly each step of the algorithm and look at the results. (Someone else can
perform this step.)
3. Are all your predictions from 4.2 accomplished? Measurement units are preserved?
4. Do the units make sense?
5. Is reasonable the order of magnitude of results?
6. Does it work for boundary values?
7. Do every variable has an initial value?
8. Interpret the result to write down an explanation of it (how it was produced) and assign
units.
Page 16 of 77
Figure4:
Page 17 of 77
Problem statement with algorithm (Start next weekend)
I have a problem! I need to thank Benedicta for the birthday present she sent me. I could send a
thank you note through the mail. I could call her on the telephone. I could send her an email
message. I could drive to her house and thank her in person. In fact, there are many ways I could
thank her, but that's not the point. The point is that I must decide how I want to solve the
problem, and use the appropriate tool to implement (carry out) my plan. The postal service, the
telephone, the internet, and my automobile are tools that I can use, but none of these actually
solves my problem. In a similar way, a computer does not solve problems, it's just a tool that you
can use to implement my plan for solving the problem.
Knowing that Benedicta appreciates creative and unusual things, I have decided to hire a singing
messenger to deliver my thanks. In this context, the messenger is a tool, but one that needs
instructions from me. I have to tell the messenger where Benedicta lives, what time I would like
the message to be delivered, and what lyrics I want sung. A computer program is similar to my
instructions to the messenger.
The story of Benedicta uses a familiar context to set the stage for a useful point of view
concerning computers and computer programs. The following list summarizes the key aspects of
this point of view.
• A computer is a tool that can be used to implement a plan for solving a problem.
• A computer program is a set of instructions for a computer. These instructions describe
the steps that the computer must follow to implement a plan.
• An algorithm is a plan for solving a problem.
• A person must design an algorithm.
• A person must translate an algorithm into a computer program.
This point of view sets the stage for a process that we will use to develop solutions to problems.
The basic process is important because it can be used to solve a wide variety of problems,
including the ones where the solution will be written in some other programming language.
There are many ways to write an algorithm. Some are very informal, some are quite formal and
mathematical in nature, and some are quite graphical. The instructions for connecting a DVD
player to a television is an algorithm. A mathematical formula such as πR2 is a special case of an
algorithm. The form is not particularly important as long as it provides a good way to describe
and check the logic of the plan.
The development of an algorithm (a plan) is a key step in solving a problem. Once we have an
algorithm, we can translate it into a computer program using some programming language. The
algorithm development process consists of five major steps.
The client is responsible for creating a description of the problem, but this is often the weakest
part of the process. It's quite common for a problem description to suffer from one or more of the
following types of defects: (1) the description relies on unstated assumptions, (2) the description
is ambiguous, (3) the description is incomplete, or (4) the description has internal contradictions.
These defects are seldom due to carelessness by the client. Instead, they are due to the fact that
natural languages (English, French, etc.) are rather imprecise. The developer's responsibility is to
identify the defects in the description of a problem, and work with the client to remedy those
defects.
For instance, when determining the starting point, we should start by seeking answers to the
following questions:
• What data are available?
• Where is that data?
• What formulas pertain to the problem?
• What rules exist for working with the data?
• What relationships exist among the data values?
When determining the ending point, we need to describe the characteristics of a solution. In other
words, how will we know when we're done? Asking the following questions often helps to
determine the ending point.
• What new facts will we have?
• What items will we have changed?
• What changes will we have to make to those items?
• What things will no longer exist?
Analysis: I don't have a card. I prefer to buy a card rather than make one myself.
Page 19 of 77
High-level algorithm:
This algorithm is satisfactory for daily use, but it lacks details that would have to be added when
using computer to carry out the solution. These details include answers to questions such as the
following.
• "Which store will I visit?"
• "How will I get there: walk, drive, ride a bicycle, take a bus or tri-cycle?"
• "What kind of card does Michael like: humorous or sentimental?"
These kinds of details are considered in the next step of our process.
When our goal is to develop algorithms that will lead to computer programs, we need to consider
the capabilities of the computer and provide enough detail so that someone else could use our
algorithm to write a computer program that follows the steps in our algorithm. As with the
birthday card problem, we need to adjust the level of detail to match the ability of the
programmer.
Most of our examples will move from a high-level algorithm to a detailed algorithm in a single
step. This technique of gradually working from a high-level to a detailed algorithm is often
called stepwise refinement. In other words, stepwise refinement is a process for developing a
detailed algorithm by gradually adding detail to a high-level algorithm.
• Does this algorithm solve a very specific problem or does it solve a more general
problem? If it solves a very specific problem, should it be generalized?
For example, an algorithm that computes the area of a circle having radius 5.2 meters
(formula π*5.22) solves a very specific problem, but an algorithm that computes the area
of any circle (formula π*R2) solves a more general problem.
Page 20 of 77
• Can this algorithm be simplified?
One formula for computing the perimeter of a rectangle is:
length + width + length + width
A simpler formula would be:
2.0 * (length + width)
• Is this solution similar to the solution to another problem? How are they alike? How are
they different?
Definition of an Algorithm
Algorithms have been defined as "... rules for calculating something, especially by machine" (2).
They are rules that can be followed more or less automatically by reasonably intelligent systems,
such as a computer.
Step :
Start by converting grams of AgBr into moles of AgBr.
Convert moles of AgBr into moles of Br, and then convert moles of Br into grams of Br.
Subtract grams of Br from grams of indium bromide to give grams of In.
Convert grams of In into moles of In.
Then divide moles of Br by moles of In to get the empirical formula of the compound.
The description given above is an algorithm that can be used for solving similar questions.
A problem reads,
Whenever there is a gap between where you are now and where you want to be, and you don’t
know how to find a way to cross that gap, you have a problem.
His definition provides a basis for distinguishing between two closely related concepts, exercises
and problems.
According to this definition, if you know what to do when you read a question, it is an exercise
or assignment but not a problem. The indium bromide question was a problem for every student
chemistry class
Page 21 of 77
The Role of Algorithms in Working Exercises
Algorithms are useful for solving routine questions or exercises. In fact, the existence of an
algorithm constructed from prior experience (4) may be what turns a question into an exercise.
What is the empirical formula of a compound of xenon and oxygen which is 67.2% Xe and
32.8% O?
Pseudo-Code Statements
Output
Input
Process
Decision
Repetition
Variables -Are symbols used to store values. The value stored can change during the algorithm
Pseudo-Code: Output
Output are used to display information
General format:
Line of text: Output 'Message'
Variable: Output Name of variable
Page 22 of 77
Example
Output 'Available credit limit: ' limit
Pseudo-Code: Input
It is used to get information
Information is stored in a variable
General format:
Input: Name of variable
Example:
Input user_name
Pseudo-Code: Process
Process is used for computer programs. it's usually an assignment statement (sets a variable to
some value)
General form:
if (condition is met) then
statement(s)
else
statements(s)
Example:
if (at work) then
Dress formally
else
Dress casually
Pseudo-Code: Repetition
repeat-until
while-do
Page 23 of 77
General form:
repeat
statement(s)
until (condition is met)
Example:
repeat
Go up to buffet table
until full
Page 25 of 77
Flowchart Symbols
Flowcharts use special shapes to represent different types of actions or steps in a process. Lines
and arrows show the sequence of the steps, and the relationships among them. These are known
as flowchart symbols.
The type of diagram dictates the flowchart symbols that are used. For example, a data flow
diagram may contain an Input/Output Symbol (also known as an I/O Symbol), but you wouldn't
expect to see it in most process flow diagrams.
Over the years, as technology has evolved, so has flowcharting. Some flowchart symbols that
were used in the past to represent computer punchcards, or punched tape, have been relegated to
the dustbin of history.
Page 26 of 77
More Flowchart Symbols
Start/End Symbol
The terminator symbol marks the starting or ending point of the
system. It usually contains the word "Start" or "End."
Action or Process Symbol
A box can represent a single step ("add two cups of flour"), or and
entire sub-process ("make bread") within a larger process.
Document Symbol
A printed document or report.
Multiple Documents Symbol
Represents multiple documents in the process
Decision Symbol
A decision or branching point. Lines representing different decisions
emerge from different points of the diamond
Input/Output Symbol
Represents material or information entering or leaving the system,
such as customer order (input) or a product (output).
Manual Input Symbol - Represents a step where a user is prompted
to enter information manually.
Page 27 of 77
Preparation Symbol
Represents a set-up to another step in the process.
Or Symbol
Indicates that the process flow continues in more than two branches.
Page 28 of 77
Flowchart: Fast Food Example
Draw a flowchart to outline the algorithm for a person who ordering food at a fast food
restaurant. At the food counter, the person can either order not order the following items: a
burger, fries and a drink. After placing her order the person then goes to the cashier.
Page 29 of 77
Flowchart: ATM Example
Draw a flowchart to outline the algorithm for an ATM bank machine. The bank machine has four
options: 1) Show current balance 2) Deposit money 3) Withdraw money 4) Quit. After an option
has been selected, the ATM will continue displaying the four options to the person until he
selects the option to quit the ATM.
Page 30 of 77
Problem Solving Strategies (Begin with Angela)
What Are Problem Solving Strategies?
Strategies are things that we choose from, in the second stage of problem solving and is used in
Page 31 of 77
the third stage. In other words, strategies are things we use to solve a problem but couldn’t
guarantee the soln. So they are some sort of general ideas that might work for a number of
problems.
We now look at each of the following strategies and discuss them in some depth. You will see
that each strategy we have in our list is really only a summary of two or more others.
1 Guess
This stands for two strategies, guess and check and guess and improve.
Guess and check is one of the simplest strategies. Anyone can guess an answer. If they can also
check that the guess fits the conditions of the problem, then they have mastered guess and check.
Guessing and checking provides a useful way to start and explore a problem. At times,
exploration leads to a more efficient strategy and then to a solution.
Guess and improve is slightly more sophisticated than guess and check. The idea is that you use
your first incorrect guess to make an improved next guess. You can see it in action in the
Farmyard problem. In relatively straightforward problems like that, it is often fairly easy to see
how to improve the last guess. In some problems though, where there are more variables, it may
not be clear at first which way to change the guessing.
2 Act It Out
We put two strategies together here because they are closely related. These are Act it Out and
Use Equipment.
Young children especially, enjoy using Act it Out. There are pros and cons for this strategy. It is
an effective strategy for demonstration purposes. On the other hand, it can also be cumbersome
when large numbers of students are involved. However, found it a useful strategy when there is
difficulty in understanding a problem.
Use Equipment is a strategy related to Act it Out. Generally, objects can be used in some way to
represent the situation to solve. Such objects are referred to as equipment (tools).
One of the difficulties with using equipment is keeping track of the solution. Actually the same
thing is true for acting it out. There is need to keep track of the work as the equipment is
manipulated.
Drawing tools can be used and equipment can also be used to model the solution.
Page 32 of 77
3 Draw
It is fairly clear that a picture has to be used in the strategy Draw a Picture. But the picture need
not be too elaborate. It should only contain enough detail to solve the problem.
It’s hard to know where Drawing a Picture ends and Drawing a Diagram begins. You might
think of a diagram as anything that you can draw which isn’t a picture. Venn diagrams and tree
diagrams are particular types of diagrams that we use so often they have been given names in
their own right.
It’s probably worth saying at this point that acting it out, drawing a picture, drawing a diagram,
and using equipment, may just be disguises for guessing and checking or even guessing and
improving.
4 Make a list
Making Organized Lists and Tables are two aspects of working systematically. It helps to bring
a logical and systematic development to the problem if we begin to organize things
systematically as we go.
There are a number of ways of using Make a Table. Tables can also be an efficient way of
finding number patterns.
When an Organized List is being used, it should be arranged in such a way that there is some
natural order implicit in its construction. For example, shopping lists are generally not organized.
They usually grow haphazardly as you think of each item. A little thought might make them
organized. Putting all the meat together, all the vegetables together, and all the drinks together,
could do this for you. Even more organization could be forced by putting all the meat items in
alphabetical order, and so on. Someone we know lists the items on her list in the order that they
appear on her route through the supermarket.
5 Think
In many ways we are using this strategy category as a catch-all. This is partly because these
strategies are not usually used on their own but in combination with other strategies.
The strategies that we want to mention here are Being Systematic, Keeping Track, Looking For
Patterns, Use Symmetry and Working Backwards and Use Known Skills.
Being Systematic, Keeping Track, Looking For Patterns and Using Symmetry are different from
the strategies we have talked about above in that they are over-arching strategies. In all problem
solving, and indeed in all mathematics, you need to keep these strategies in mind.
Being systematic may mean making a table or an organised list but it can also mean keeping
your working in some order so that it is easy to follow when you have to go back over it. It
means that you should work logically as you go along and make sure you don’t miss any steps in
an argument. And it also means following an idea for a while to see where it leads, rather than
jumping about all over the place chasing lots of possible ideas.
It is very important to keep track of your work. Keeping track is particularly important with Act
it Out and Using Equipment. But it is important in many other situations too. This begins to be
more significant as the problems get more difficult and involve more and more steps.
Page 33 of 77
In many ways looking for patterns is what mathematics is all about. We want to know how
things are connected and how things work and this is made easier if we can find patterns.
Patterns make things easier because they tell us how a group of objects acts in the same way.
Once we see a pattern we have much more control over what we are doing.
Using symmetry helps us to reduce the difficulty level of a problem. Playing Noughts and
crosses, for instance, you will have realized that there are three and not nine ways to put the first
symbol down. This immediately reduces the number of possibilities for the game and makes it
easier to analyze. This sort of argument comes up all the time and should be grabbed with glee
when you see it.
Finally working backwards is a standard strategy that only seems to have restricted use.
However, it’s a powerful tool when it can be used. In the kind of problems we will be using in
this web-site, it will be most often of value when we are looking at games. It frequently turns out
to be worth looking at what happens at the end of a game and then work backward to the
beginning, in order to see what moves are best.
Then we come to use known skills. This isn't usually listed in most lists of problem solving
strategies but as we have gone through the problems in this web site, we have found it to be quite
common. The trick here is to see which skills that you know can be applied to the problem in
hand.
This strategy is related to the first step of problem solving when the problem solver thinks 'have I
seen a problem like this before?' Being able to relate a word problem to some previously
acquired skill is not easy but it is extremely important.
Uses of Strategies
Different strategies have different uses. We’ll illustrate this by means of a problem.
The Farmyard Problem: In the farmyard there are some pigs and some chickens. In fact there
are 87 animals and 266 legs. How many pigs are there in the farmyard?
Exercise:
In the farmyard there are some lions and some ostriches. In fact there are 90 animals and 270
legs. How many lions are there in the farmyard? Write a pseudocode and flowchart to show the
solution
Some strategies help you to understand a problem. Let’s kick off with one of those. Guess and
check. Let’s guess that there are 80 pigs. If there are they will account for 320 legs. Clearly
we’ve over-guessed the number of pigs. So maybe there are only 60 pigs. Now 60 pigs would
have 240 legs. That would leave us with 16 legs to be found from the chickens. It takes 8
Page 34 of 77
chickens to produce 16 legs. But 60 pigs plus 8 chickens is only 68 animals so we have landed
nearly 20 animals short.
Obviously we haven’t solved the problem yet but we have now come to grips with some of the
important aspects of the problem. We know that there are 87 animals and so the number of pigs
plus the number of chickens must add up to 87. We also know that we have to use the fact that
pigs have four legs and chickens two, and that there have to be 266 legs altogether.
Some strategies are methods of solution in themselves. For instance, take Guess and Improve.
Supposed we guessed 60 pigs for a total of 240 legs. Now 60 pigs imply 27 chickens, and that
gives another 54 legs. Altogether then we’d have 294 legs at this point.
Unfortunately we know that there are only 266 legs. So we’ve guessed too high. As pigs have
more legs than hens, we need to reduce the guess of 60 pigs. How about reducing the number of
pigs to 50? That means 37 chickens and so 200 + 74 = 274 legs.
We’re still too high. Now 40 pigs and 47 hens gives 160 + 94 = 254 legs. We’ve now got too few
legs so we need to guess more pigs.
You should be able to see now how to oscillate backwards and forwards until you hit on the right
number of pigs. So guess and improve is a method of solution that you can use on a number of
problems.
Some strategies can give you an idea of how you might tackle a problem. Making a Table
illustrates this point. We’ll put a few values in and see what happens. 2 x number of chicken + 4
x number of pigs = total number of legs
From the table we can see that every time we change the number of pigs by one, we change the
number of legs by two. This means that in our last guess in the table, we are five pigs away from
the right answer. Then there have to be 46 pigs.
1 PRINT "A GAME TO FIND THE NUMBER OF PIGS AND CHICKEN FROM 2 A GIVEN NUMBER OF
ANIMALS"
3 LET TOTALANIMALS$ = 87
4 LET TOTALANIMALSLEGS$ = 266
5 LET NUMBEROFCHCIKEN$ = 0
6 PRINT "ENTER NUMBER OF PIGS"
7 INPUT NUMBEROFPIG$
8 PRINT "ENTER NUMBER OF PIGS"NUMBEROFPIG$
9 NUMBEROFCHICKEN$ = TOTALANIMALS$ - NUMBEROFPIGS$
10 IF (NUMBEROFCHICKEN$*2)+(NUMBEROFPIGS$*4)= TOTALANIMALSLEGS$ THEN GOTO 11
ELSE GOTO 13
Page 35 of 77
11 PRINT "NUMBER OF PIGS" NUMBEROFPIGS$ "AND NUMBER OF CHICKEN"
NUMBEROFCHICKEN$ "YOU ENTERED ARE CORRECT"
12 GOTO 14
13 GOTO 6
14 END
Some strategies help us to see general patterns so that we can make conjectures. Some strategies
help us to see how to justify conjectures. And some strategies do other jobs. We’ll develop these
ideas on the uses of strategies as this web-site grows.
We have observed the following strategies being used in the stated Levels.
Levels 1 and 2
• Draw a Picture
• Act it Out
• Use Equipment
• Guess and Check
Levels 3 and 4
• Draw a Diagram
• Act it Out
• Use Equipment
• Guess and Improve
• Make a Table
• Make an Organised List
The simple "draw a picture" eventually develops into a wide variety of drawings that enable
children, and adults, to solve a vast array of problems.
Guess: Moving from guess and check to guess and improve, is an obvious development of a
simple strategy. Guess and check may work well in some problems but guess and improve is a
simple development of guess and check.
Implementation Strategy
Monitoring progress
Your implementation will only be successful if you are monitoring your solution, the effects of it
on resources and stakeholders, your timeline, and your progress. As you monitor your progress,
if results are not what you expect, review your options and alternatives.
Properties of an algorithm:
- Should be written in simple English
- Should be unambiguous, precise and lucid
- Should provide the correct solutions
- Should have an end point
- The output statements should follow input, process instructions
- The initial statements should be of input statements
Page 37 of 77
- Should have finite number of steps
- Every statement should be definitive
Types of algorithms:
– Simple recursive algorithms. Ex: Searching an element in a list
– Backtracking algorithms Ex: Depth-first recursive search in a tree
– Divide and conquer algorithms. Ex: Quick sort and merge sort
– Dynamic programming algorithms. Ex: Generation of Fibonacci series
– Greedy algorithms Ex: Counting currency
– Branch and bound algorithms. Ex: Travelling salesman (visiting each city once and minimize
the total distance travelled)
– Brute force algorithms. Ex: Finding the best path for a travelling salesman
– Randomized algorithms. Ex. Using a random number to choose a pivot in quick sort).
PROGRAM DEVELOPMENT
Program Object
Emphasis will be with Visual Studio .NET (Any version)
Page 38 of 77
The Program object is used to examine and manipulate programs. This object can be used to
check and see if a program is being debugged, and a program's process can be examine and
threads managed by the program.
Properties are retrieved and set like fields, but are implemented by property Get and
property Set procedures, which provide more control on how values are set or returned. The
layer of indirection between the value being stored and the procedures that use this value helps
isolate your data and lets you validate values before they are assigned or retrieved.
Methods represent actions that an object can perform. For example, a "Car" object could have
"StartEngine," "Drive," and "Stop" methods. Methods are defined by adding procedures,
either Sub routines or functions, to your class.
Events are notifications an object receives from, or transmits to, other objects or applications.
Events enable objects to perform actions whenever a specific occurrence occurs. An example of
an event for the "Car" class would be a "Check_Engine" event. Because Microsoft Windows is
an event-driven operating system, events can come from other objects, applications, or user input
such as mouse clicks or key presses.
Encapsulation means that a group of related properties, methods, and other members are treated
as a single unit or object. Objects can control how properties are changed and methods are
executed. For example, an object can validate values before enabling property changes.
Encapsulation also makes it easier to change your implementation at a latter date by letting you
hide implementation details of your objects, a practice called data hiding.
Inheritance describes the ability to create new classes based on an existing class. The new class
inherits all the properties and methods and events of the base class, and can be customized with
Page 39 of 77
additional properties and methods. For example, you can create a new class named "Truck"
based on the "Car" class. The "Truck" class inherits the "Color" property from the "Car" class
and can have additional properties such as "FourWheelDrive."
Polymorphism means that you can have multiple classes that can be used interchangeably, even
though each class implements the same properties or methods in different ways. Polymorphism
is important to object-oriented programming because it lets you use items with the same names,
regardless of what type of object is in use at the moment. For example, given a base class of
"Car," polymorphism enables the programmer to define different "StartEngine" methods for any
number of derived classes. The "StartEngine" method of a derived class named "DieselCar" may
be completely different from the method with the same name in the base class. Other procedures
or methods can use the "StartEngine" method of the derived classes in the same way, no matter
what type of "Car" object is being used at the time.
Operators
An operator is a special symbol which indicates a certain process is carried out. Operators in
programming languages are taken from mathematics. Programmers work with data. The
operators are used to process data.
An operator may have one or two operands. An operand is one of the inputs (arguments) of an
operator. Those operators that work with only one operand are called unary operators. Those
who work with two operands are called binary operators.
Option Strict On
Module Example
Sub Main()
Console.WriteLine(2)
Console.WriteLine(-2)
Console.WriteLine(2+2)
Console.WriteLine(2-2)
End Sub
Page 40 of 77
End Module
The + and - signs can be addition and subtraction operators as well as unary sign operators. It
depends on the situation.
Option Strict On
Module Example
Dim a As Byte
Sub Main()
a=1
Console.WriteLine(-a) ' Prints -1
Console.WriteLine(-(-a)) ' Prints 1
End Sub
End Module
The plus sign can be used to indicate that we have a positive number. But it is mostly not used.
The minus sign changes the sign of a value.
Option Strict On
Module Example
Dim a As Byte
Dim b As Byte
Sub Main()
a=3*3
b=2+2
Console.WriteLine(a) ' Prints 9
Console.WriteLine(b) ' Print 4
End Sub
End Module
Multiplication and addition operators are examples of binary operators. They are used with two
operands.
The assignment operator = assigns a value to a variable. A variable is a placeholder for a value.
In mathematics, the = operator has a different meaning. In an equation, the = operator is an
equality operator. The left side of the equation is equal to the right one.
x=1
Console.WriteLine(x) ' Prints 1
The previous expression does not make sense in mathematics. But it is legal in programming.
The expression adds 1 to the x variable. The right side is equal to 2 and 2 is assigned to x.
Page 41 of 77
3=x
This code example results in syntax error. We cannot assign a value to a literal.
Arithmetic operators
Symbol Name
+ Addition
- Subtraction
* Multiplication
/ Division
\ Integer Division
Mod Modulo
^ Exponentiation
Module Example
Dim a As Byte
Dim b As Byte
Dim c As Byte
Sub Main()
a = 10
b = 11
c = 12
add = a + b + c
sb = c - a
mult = a * b
div = CType(c / 3, Byte)
Console.WriteLine(add)
Console.WriteLine(sb)
Console.WriteLine(mult)
Console.WriteLine(div)
End Sub
End Module
Page 42 of 77
In the preceding example, we use addition, subtraction, multiplication and division operations.
This is all familiar from the mathematics.
$ ./arithmetic.exe
33
2
110
4
Next we will show the distinction between normal and integer division.
Option Strict On
Module Example
Dim a As Single = 5
Dim b As Single = 2
Dim c As Single
Sub Main()
c=5/2
Console.WriteLine(c)
c=5\2
Console.WriteLine(c)
End Sub
End Module
In the preceding example, we divide two numbers using normal and integer division operator.
Visual Basic has two distinct operators for division.
Dim a As Single = 5
c=5/2
Console.WriteLine(c)
c=5\2
Console.WriteLine(c)
This is integer division. The result of this operation is always and integer. The c variable has
value 2.
$ ./division.exe
2.5
2
Result of the division.exe program.
Page 43 of 77
The last two operators that we will mention are modulo operator and exponentiation operator.
Console.WriteLine(9 Mod 4) ' Prints 1
The Mod operator is called the modulo operator. It finds the remainder of division of one number
by another. 9 Mod 4, 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder of 1. Modulo
operator can be handy for example when we want to check for prime numbers.
9 ^ 2 = 9 * 9 = 81
Boolean operators
In Visual Basic, we have the following logical operators. Boolean operators are also called
logical.
Symbol Name
And logical conjunction
AndAlso short circuit And
Or logical inclusion
OrElse short circuit Or
Xor logical inclusion
Not negation
Option Strict On
Module Example
Dim x As Byte = 3
Dim y As Byte = 8
Sub Main()
Console.WriteLine(x = y)
Console.WriteLine(y > x)
If (y > x)
Console.WriteLine("y is greater than x")
End If
End Sub
End Module
Many expressions result in a boolean value. Boolean values are used in conditional statements.
Page 44 of 77
Console.WriteLine(x = y)
Console.WriteLine(y > x)
Relational operators always result in a Boolean value. These two lines print False and True.
If (y > x)
Console.WriteLine("y is greater than x")
End If
The body of the If statement is executed only if the condition inside the parentheses is met. The x
> y returns True, so the message "y is greater than x" is printed to the terminal.
Option Strict On
Module Example
Dim a As Boolean
Dim b As Boolean
Dim c As Boolean
Dim d As Boolean
Sub Main()
Console.WriteLine(a)
Console.WriteLine(b)
Console.WriteLine(c)
Console.WriteLine(d)
End Sub
End Module
Example shows the logical And operator. It evaluates to True only if both operands are True.
$ ./andop.exe
True
False
False
False
The logical Xor operator evaluates to True, if exactly one of the operands is True.
Option Strict On
Page 45 of 77
Module Example
Dim a As Boolean
Dim b As Boolean
Dim c As Boolean
Dim d As Boolean
Sub Main
Console.WriteLine(a)
Console.WriteLine(b)
Console.WriteLine(c)
Console.WriteLine(d)
End Sub
End Module
The logical Xor evaluates to False if both operands are True or both False.
$ ./xorop.exe
False
True
True
False
Option Strict On
Module Example
Sub Main()
Console.WriteLine(a)
Console.WriteLine(b)
Console.WriteLine(c)
Page 46 of 77
Console.WriteLine(d)
End Sub
End Module
If one of the sides of the operator is True, the outcome of the operation is True.
$ ./orop.exe
True
True
True
False
The negation operator Not makes True False and False True.
Option Strict On
Module Example
Sub Main()
Console.WriteLine(Not True)
Console.WriteLine(Not False)
Console.WriteLine(Not (4 < 3))
End Sub
End Module
Relational Operators
Relational operators are used to compare values. These operators always result in a boolean
value.
Symbol Meaning
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
<> not equal to
Is compares references
Page 47 of 77
Console.WriteLine(3 < 4) ' Prints True
Console.WriteLine(3 = 4) ' Prints False
Console.WriteLine(4 >= 3) ' Prints True
As we already mentioned, the relational operators return boolean values. Note that in Visual
Basic, the comparison operator is =. Not == like in C and C influenced languages.
Notice that the relational operators are not limited to numbers. We can use them for other objects
as well. Although they might not always be meaningful.
Option Strict On
Module Example
Sub Main()
End Sub
End Module
We can compare string objects too. Comparison operators in a string context compare the sorting
order of the characters.
What exactly happens here? Computers do not know characters or strings. For them, everything
is just a number. Characters are special numbers stored in specific tables. Like ASCII.
Option Strict On
Module Example
Sub Main()
End Sub
End Module
Page 48 of 77
Internally, the a and b characters are numbers. So when we compare two characters, we compare
their stored numbers. The built-in Asc function returns the ASCII value of a single character.
$ ./compare.exe
True
a is: 97
b is: 98
Say we have a string with more characters. If the first characters are equal, we compare the next
ones. In our case, the b character at the second position has a greater value than the a character.
That is why "ab" string is greater than "aa" string. Comparing strings in such a way does not
make much sense, of course. But it is technically possible.
Finally, we will mention the Is operator. The operator checks if two object references refer to the
same object. It does not perform value comparisons.
Option Strict On
Module Example
Sub Main()
o3 = o2
Console.WriteLine(o1 Is o2)
Console.WriteLine(o3 Is o2)
End Sub
End Module
We declare and initialise two Object instances. The Object class is a base class for all classes in
the .NET framework. We will describe it later in more detail.
Dim o3 As Object
Page 49 of 77
The third variable is only declared.
o3 = o2
The o3 now refers to the o2 object. They are two references to the same object.
Console.WriteLine(o1 Is o2)
Console.WriteLine(o3 Is o2)
In the first case, we get False. The o1 and o2 are two different objects. In the second case, we get
True. The o3 and o2 refer to the same object.
Bitwise operators
Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal,
decimal, or hexadecimal symbols are only notations of the same number. Bitwise operators work
with bits of a binary number. Bitwise operators are seldom used in higher level languages like
Visual Basic.
Symbol Meaning
Not bitwise negation
Xor bitwise exclusive or
And bitwise and
Or bitwise or
The operator reverts all bits of a number 7. One of the bits also determines, whether the number
is negative or not. If we negate all the bits one more time, we get number 7 again.
The bitwise and operator performs bit-by-bit comparison between two numbers. The result for a
bit position is 1 only if both corresponding bits in the operands are 1.
00110
And 00011
= 00010
The first number is a binary notation of 6, the second is 3 and the result is 2.
The bitwise or operator performs bit-by-bit comparison between two numbers. The result for a
bit position is 1 if either of the corresponding bits in the operands is 1.
Page 50 of 77
00110
Or 00011
= 00111
The bitwise exclusive or operator performs bit-by-bit comparison between two numbers. The
result for a bit position is 1 if one or the other (but not both) of the corresponding bits in the
operands is 1.
00110
Xor 00011
= 00101
Operator precedence
The operator precedence tells us which operators are evaluated first. The precedence level is
necessary to avoid ambiguity in expressions.
3+5*5
Like in mathematics, the multiplication operator has a higher precedence than addition operator.
So the outcome is 28.
(3 + 5) * 5
To change the order of evaluation, we can use parentheses. Expressions inside parentheses are
always evaluated first.
The following list shows common Visual Basic operators ordered by precedence (highest
precedence first):
Operator(s) Description
^ exponentiation
+- unary identity and negation
*/ multiplication, float division
\ integer division
Mod modulus
Page 51 of 77
+- addition, subtraction, string concatenation
& string concatenation
<< >> arithmetic bit shift
= <> < > >= <= Is IsNot Like TypeOf Is All comparison operators
Not negation
And AndAlso conjunction
Or OrElse Inclusive disjunction
Xor Exclusive disjunction
Operators on the same line in the list have the same precedence.
Option Strict On
Module Example
Sub Main()
Console.WriteLine(3 + 5 * 5)
Console.WriteLine((3 + 5) * 5)
End Sub
End Module
In this code example, we show some common expressions. The outcome of each expression is
dependent on the precedence level.
Console.WriteLine(3 + 5 * 5)
This line prints 28. The multiplication operator has a higher precedence than addition. First the
product of 5*5 is calculated. Then 3 is added.
In this case, the negation operator has a higher precedence. First, the first True value is negated
to False, than the Or operator combines False and True, which gives True in the end.
$ ./precedence.exe
28
40
True
False
Associativity
Page 52 of 77
Sometimes the precedence is not satisfactory to determine the outcome of an expression. There is
another rule called associativity. The associativity of operators determines the order of
evaluation of operators with the same precedence level.
9/3*3
What is the outcome of this expression? 9 or 1? The multiplication, deletion and the modulo
operator are left to right associated. So the expression is evaluated this way: (9 / 3) * 3 and the
result is 9.
Arithmetic, boolean, relational and bitwise operators are all left o right associated.
a=b=c=d=0
Console.WriteLine("{0} {1} {2} {3}", a, b, c, d) ' Prints 0 0 0 0
If the association was left to right, the previous expression would not be possible.
j=0
j *= 3 + 1
Console.WriteLine(j)
You might expect the result to be 1. But the actual result is 0. Because of the associativity. The
expression on the right is evaluated first and than the compound assignment operator is applied.
An operator is a code element that performs an operation on one or more code elements that
hold values. Value elements include variables, constants, literals, properties, returns
from Function and Operator procedures, and expressions.
An expression is a series of value elements combined with operators, which yields a new value.
The operators act on the value elements by performing calculations, comparisons, or other
operations.
Types of Operators
Visual Basic provides the following types of operators:
• Arithmetic Operators perform familiar calculations on numeric values, including shifting
their bit patterns.
• Comparison Operators compare two expressions and return a Boolean value representing
the result of the comparison.
• Concatenation Operators join multiple strings into a single string.
• Logical and Bitwise Operators in Visual Basic combine Boolean or numeric values and
return a result of the same data type as the values.
The value elements that are combined with an operator are called operands of that operator.
Operators combined with value elements form expressions, except for the assignment operator,
which forms a statement. For more information, see Statements.
Page 53 of 77
Evaluation of Expressions
The end result of an expression represents a value, which is typically of a familiar data type such
as Boolean, String, or a numeric type.
The following are examples of expressions.
5+4
' The preceding expression evaluates to 9.
15 * System.Math.Sqrt(9) + x
' The preceding expression evaluates to 45 plus the value of x.
"Concat" & "ena" & "tion"
' The preceding expression evaluates to "Concatenation".
763 < 23
' The preceding expression evaluates to False.
Several operators can perform actions in a single expression or statement, as the following
example illustrates.
VB
x = 45 + y * z ^ 2
In the preceding example, Visual Basic performs the operations in the expression on the right
side of the assignment operator (=), then assigns the resulting value to the variable x on the left.
There is no practical limit to the number of operators that can be combined into an expression,
but an understanding of Operator Precedence in Visual Basic is necessary to ensure that you get
the results you expect.
Page 54 of 77
Modulus arithmetic (Mod)
Addition and subtraction (+, –)
String concatenation (&)
Arithmetic bit shift (<<, >>)
Comparison Operators
All comparison operators (=, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf...Is)
Logical and Bitwise Operators
Negation (Not)
Conjunction (And, AndAlso)
Inclusive disjunction (Or, OrElse)
Exclusive disjunction (Xor)
Comments
The = operator is only the equality comparison operator, not the assignment operator.
The string concatenation operator (&) is not an arithmetic operator, but in precedence it is
grouped with the arithmetic operators.
The Is and IsNot operators are object reference comparison operators. They do not compare the
values of two objects; they check only to determine whether two object variables refer to the
same object instance.
Associativity
When operators of equal precedence appear together in an expression, for example multiplication
and division, the compiler evaluates each operation as it encounters it from left to right. The
following example illustrates this.
Dim n1 As Integer = 96 / 8 / 4
Dim n2 As Integer = (96 / 8) / 4
Dim n3 As Integer = 96 / (8 / 4)
The first expression evaluates the division 96 / 8 (which results in 12) and then the division 12 /
4, which results in three. Because the compiler evaluates the operations for n1 from left to right,
the evaluation is the same when that order is explicitly indicated for n2. Both n1 and n2 have a
result of three. By contrast, n3 has a result of 48, because the parentheses force the compiler to
evaluate 8 / 4 first. Because of this behavior, operators are said to be left associative in Visual
Basic.
Assignment Statements
Assignment statements carry out assignment operations, which consist of taking the value on the
right side of the assignment operator (=) and storing it in the element on the left, as in the
following example.
VB
v = 42
In the preceding example, the assignment statement stores the literal value 42 in the variable v.
You can also assign Boolean values, using either a Boolean literal or a Boolean expression, as
the following example illustrates.
VB
Dim r, s, t As Boolean
r = True
s = 45 > 1003
t = 45 > 1003 Or 45 > 17
' The preceding statements assign False to s and True to t.
Similarly, you can assign appropriate values to programming elements of the Char, Date,
or Object data type. You can also assign an object instance to an element declared to be of the
class from which that instance is created.
Page 56 of 77
Dim q As String = "Sample "
q &= "String"
' q now contains "Sample String".
In brief, Visual Basic automatically converts a value of a given type to any other type to which it
widens. A widening conversion is one in that always succeeds at run time and does not lose any
data. For example, Visual Basic converts an Integer value to Double when appropriate,
because Integer widens to Double.
Page 57 of 77
Initial Values
When the code containing a declaration statement runs, Visual Basic reserves the memory
required for the declared element. If the element holds a value, Visual Basic initializes it to the
default value for its data type.
You can assign an initial value to a variable as part of its declaration, as the following example
illustrates.
VB
Dim m As Integer = 45
' The preceding declaration creates m and assigns the value 45 to it.
If a variable is an object variable, you can explicitly create an instance of its class when you
declare it by using the New Operator keyword, as the following example illustrates.
VB
Dim f As New System.Windows.Forms.Form()
Note that the initial value you specify in a declaration statement is not assigned to a variable until
execution reaches its declaration statement. Until that time, the variable contains the default
value for its data type.
Executable Statements
An executable statement performs an action. It can call a procedure, branch to another place in
the code, loop through several statements, or evaluate an expression. An assignment statement is
a special case of an executable statement.
The following example uses an If...Then...Else control structure to run different blocks of code
based on the value of a variable. Within each block of code, a For...Next loop runs a specified
number of times.
Assignment Statements
Assignment statements carry out assignment operations, which consist of taking the value on the
right side of the assignment operator (=) and storing it in the element on the left, as in the
following example.
VB
v = 42
In the preceding example, the assignment statement stores the literal value 42 in the variable v.
Adding Comments
Source code is not always self-explanatory, even to the programmer who wrote it. To help
document their code, therefore, most programmers make liberal use of embedded comments.
Comments in code can explain a procedure or a particular instruction to anyone reading or
working with it later. Visual Basic ignores comments during compilation, and they do not affect
the compiled code.
Comment lines begin with an apostrophe (') or REM followed by a space. They can be added
anywhere in code, except within a string. To append a comment to a statement, insert an
apostrophe or REM after the statement, followed by the comment. Comments can also go on
their own separate line. The following example demonstrates these possibilities.
VB
' This is a comment on a separate code line.
REM This is another comment on a separate code line.
Term Definition
How to: Break and Shows how to break a single statement into multiple
Combine Statements in lines and how to place multiple statements on the
Code same line.
Page 59 of 77
Boolean Expressions (Visual Basic)
A Boolean expression is an expression that evaluates to a value of the Boolean Data
Type: True or False. Boolean expressions can take several forms. The simplest is the direct
comparison of the value of a Boolean variable to a Boolean literal, as shown in the following
example.
VB
If newCustomer = True Then
' Insert code to execute if newCustomer = True.
Else
' Insert code to execute if newCustomer = False.
End If
Comparison Operators
Comparison operators such as =, <, >, <>, <=, and >= produce Boolean expressions by
comparing the expression on the left side of the operator to the expression on the right side of the
operator and evaluating the result as True or False. The following example illustrates this.
42 < 81
Because 42 is less than 81, the Boolean expression in the preceding example evaluates to True.
Parenthetical Expressions
You can use parentheses to control the order of evaluation of Boolean expressions. Expressions
enclosed by parentheses evaluate first. For multiple levels of nesting, precedence is granted to
the most deeply nested expressions. Within parentheses, evaluation proceeds according to the
rules of operator precedence.
VB is case insensitive, so ss and SS is the same variable, so the compiler correctly complains
that you re-declared the variable. I think that Variables are not case sensitive, but function
names are. Yes, VB is case insensitive.
• Object - Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors - wagging, barking, eating, etc. An object is an instance of a
class.
Page 60 of 77
• Methods - A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are
executed.
• Instance Variables - Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.
Let us look at an implementation of a Rectangle class and discuss VB.Net basic syntax on the
basis of our observations in it:
Imports System
Public Class Rectangle
Private length As Double
Private width As Double
'Public methods
Public Sub AcceptDetails()
length = 4.5
width = 3.5
End Sub
End Sub
Length: 4.5
Width: 3.5
Area: 15.75
Identifiers
An identifier is a name used to identify a class, variable, function, or any other user-defined
item. The basic rules for naming classes in VB.Net are as follows:
• A name must begin with a letter that could be followed by a sequence of letters, digits (0
- 9) or underscore. The first character in an identifier cannot be a digit.
VB.Net Keywords
The following table lists the VB.Net reserved keywords:
Namespace
Page 62 of 77
Inheritable Overridable
Handler
An identifier is a name. Visual Basic .NET identifiers conform to the Unicode Standard Annex
15 with one exception: identifiers may begin with an underscore (connector) character. If an
identifier begins with an underscore, it must contain at least one other valid identifier character to
disambiguate it from a line continuation.
Regular identifiers may not match keywords, but escaped identifiers can. An escaped identifier is
an identifier delimited by square brackets. Escaped identifiers follow the same rules as regular
identifiers except that they may match keywords and may not have type characters.
Scope
Scope refers to the so-called visibility of identifiers within source code. That is, given a
particular identifier declaration, the scope of the identifier determines where it is legal to
reference that identifier in code. For example, these two functions each declare a
variable CoffeeBreaks. Each declaration is invisible to the code in the other method. The scope
of each variable is the method in which it is declared.
Unlike previous versions of Visual Basic, Visual Basic .NET has block scope. Variables declared
within a set of statements ending with End, Loop, or Nextare local to that block. For example:
Dim i As Integer
Page 63 of 77
For i = 1 To 100
Dim j As Integer
For j = 1 To 100
' ...
Next
Next
' j is not visible here
Visual Basic .NET doesn’t permit the same variable name to be declared at both the method
level and the block level. Further, the life of the block-level variable is equal to the life of the
method. This means that if the block is re-entered, the variable may contain an old value (don’t
count on this behavior, as it is not guaranteed and is the kind of thing that might change in future
versions of Visual Basic).
Page 64 of 77
Block Scope
A block is a set of statements enclosed within initiating and terminating declaration statements,
such as the following:
• Do and Loop
• For [Each] and Next
• If and End If
• Select and End Select
• SyncLock and End SyncLock
• Try and End Try
• While and End While
• With and End With
If you declare a variable within a block, you can use it only within that block. In the following
example, the scope of the integer variable cube is the block between If and End If, and you can
no longer refer to cube when execution passes out of the block.
If n < 1291 Then
Dim cube As Integer
cube = n ^ 3
End If
Even if the scope of a variable is limited to a block, its lifetime is still that of the entire
procedure. If you enter the block more than once during the procedure, each block variable
retains its previous value. To avoid unexpected results in such a case, it is wise to initialize block
variables at the beginning of the block.
Procedure Scope
An element declared within a procedure is not available outside that procedure. Only the
procedure that contains the declaration can use it. Variables at this level are also known as local
variables. You declare them with the Dim Statement, with or without the Static keyword.
Procedure and block scope are closely related. If you declare a variable inside a procedure but
outside any block within that procedure, you can think of the variable as having block scope,
where the block is the entire procedure.
All local elements, even if they are Static variables, are private to the procedure in which they
appear. You cannot declare any element using the Public keyword within a procedure.
Module Scope
For convenience, the single term module level applies equally to modules, classes, and
structures. You can declare elements at this level by placing the declaration statement outside of
any procedure or block but within the module, class, or structure.
When you make a declaration at the module level, the access level you choose determines the
scope. The namespace that contains the module, class, or structure also affects the scope.
Elements for which you declare Private access level are available to every procedure in that
module, but not to any code in a different module. The Dim statement at module level defaults
to Private if you do not use any access level keywords. However, you can make the scope and
access level more obvious by using the Private keyword in the Dim statement.
In the following example, all procedures defined in the module can refer to the string
variable strMsg. When the second procedure is called, it displays the contents of the string
variable strMsg in a dialog box.
' Put the following declaration at module level (not in any procedure).
Private strMsg As String
' Put the following Sub procedure in the same module.
Page 65 of 77
Sub initializePrivateVariable()
strMsg = "This variable cannot be used outside this module."
End Sub
' Put the following Sub procedure in the same module.
Sub usePrivateVariable()
MsgBox(strMsg)
End Sub
Namespace Scope
If you declare an element at module level using the Friend or Public keyword, it becomes
available to all procedures throughout the namespace in which the element is declared. With the
following alteration to the preceding example, the string variable strMsg can be referred to by
code anywhere in the namespace of its declaration.
' Include this declaration at module level (not inside any procedure).
Public strMsg As String
Namespace scope includes nested namespaces. An element available from within a namespace is
also available from within any namespace nested inside that namespace.
If your project does not contain any Namespace Statements, everything in the project is in the
same namespace. In this case, namespace scope can be thought of as project
scope. Public elements in a module, class, or structure are also available to any project that
references their project.
Choice of Scope
When you declare a variable, you should keep in mind the following points when choosing its
scope.
Minimizing Scope
In general, when declaring any variable or constant, it is good programming practice to make the
scope as narrow as possible (block scope is the narrowest). This helps conserve memory and
minimizes the chances of your code erroneously referring to the wrong variable. Similarly, you
should declare a variable to be Static only when it is necessary to preserve its value between
procedure calls.
Page 66 of 77
How to: Control the Scope of a Variable (Visual Basic): Visual Studio 2015
Normally, a variable is in scope, or visible for reference, throughout the region in which you
declare it. In some cases, the variable's access level can influence its scope.
Example
The following example declares a variable at module level and limits its visibility to code within
the module.
Module demonstrateScope
Private strMsg As String
Sub initializePrivateVariable()
strMsg = "This variable cannot be used outside this module."
End Sub
Sub usePrivateVariable()
MsgBox(strMsg)
End Sub
End Module
In the preceding example, all the procedures defined in module demonstrateScope can refer to
the String variable strMsg. When the usePrivateVariable procedure is called, it displays the
contents of the string variable strMsg in a dialog box.
Page 67 of 77
With the following alteration to the preceding example, the string variable strMsg can be referred
to by code anywhere in the namespace of its declaration.
Public strMsg As String
Robust Programming
The narrower the scope of a variable, the fewer opportunities you have for accidentally referring
to it in place of another variable with the same name. You can also minimize problems of
reference matching.
.NET Framework Security
The narrower the scope of a variable, the smaller the chances that malicious code can make
improper use of it.
Page 69 of 77
have exclusive access to it. Because other procedures could access applesSold and change its
value, the running total could be unreliable and the code could be more difficult to maintain.
Understanding Scope
Now that we're dividing our code into procedures, it's a good idea to look at the issue of scope
because putting code in procedures restricts that code's scope. Now that Visual Basic .NET is
emphasizing OOP more than ever before, scope has become even more important because much
of the power of classes and objects is all about restricting scope and hiding implementation
details to make things simpler.
The scope of a programming element in your code is all the code that can access it. In other
words, an element's scope is its accessibility in your code. In Visual Basic .NET, where you
declare an element determines its scope, and an element can have one of the following levels of
scope:
• Block scope—The item is available only within the code block in which it is declared.
• Procedure scope—The item is available only within the procedure in which it is
declared.
• Module scope—The item is available to all code within the module, class, or structure in
which it is declared.
• Namespace scope—The item is available to all code in the namespace.
Let's look at these various levels of scope.
Block Level
A code block is the body of a compound statement. A compound statement is one that can hold
other statements, such as an If statement. Here's an If statement in which a variable, strText, is
declared. Note that strText is inaccessible outside the If statement, so code that tries to display its
value won't work:
Module Module1
Sub Main()
Console.WriteLine
Console.WriteLine("Enter a letter...")
Dim strInput = Console.ReadLine()
If strInput = "q" Then
End
Else
Dim strText As String = "Please type q to quit."
Console.WriteLine(strText)
End If
End Module
Page 70 of 77
Procedure Level
An element declared in a procedure is not available outside that procedure, which means that
only the code in the procedure that contains the declaration can access it. Elements at this level
are called localelements, and you declare them with the Dim or Static statements. In the
following example, the variable strText declared in the ShowMessage Sub procedure cannot be
accessed in the Main Sub procedure:
Module Module1
Sub Main()
ShowMessage()
Console.WriteLine(strText) 'Will not work!
Console.WriteLine("Press Enter to continue...")
Console.ReadLine()
End Sub
Sub ShowMessage()
Dim strText = "Hi there!"
Console.WriteLine(strText)
End Sub
End Module
Module Level
Visual Basic .NET uses the term module level to apply to three programming elements: modules,
classes, and structures. You declare elements at this level by placing the declaration outside any
procedure or block in the module, class, or structure.
Unlike in blocks or procedures (where you can use only Dim or Static), at the module level you
can also use these keywords to restrict or enlarge scope. (Don't feel you have to memorize these
definitions at this stage; we'll see more on these terms throughout the book.)
• Public—The Public statement declares elements to be accessible anywhere. This includes
inside the same project, from other projects that reference the current project, assemblies
built from the project, and so on.
• Protected—The Protected statement declares elements to be accessible only from within
the same class or from a class derived from this class. You can use Protected only at class
level and only when declaring a member of a class.
• Friend—The Friend statement declares elements to be accessible from within the same
project, but not from outside the project.
• Protected Friend—The Protected statement with the Friend keyword declares elements to
be accessible either from derived classes or from within the same project, or both. You can
use Protected Friend only at class level.
• Private—The Private statement declares elements to be accessible only from within the
same module, class, or structure.
Let's look at module-level scope with some examples. For example, you can create a new code
module, Module2, like this:
Module Module1
Sub Main()
End Sub
Page 71 of 77
End Module
Module Module2
End Module
TIP
Although this example declares two modules in the same file (Module1.vb), you can also add a
module in a new file to a Visual Basic project by selecting the Project, Add Module menu item
(which will create Module2.vb, Module3.vb, and so on).
And if you declare a new Sub procedure, ShowMessage, in the new module, you can access it
from the first module:
Module Module1
Sub Main()
ShowMessage()
Console.WriteLine("Press Enter to continue...")
Console.ReadLine()
End Sub
End Module
Module Module2
Sub ShowMessage()
Console.WriteLine("Hello there!")
End Sub
End Module
However, if you declare the Sub procedure Private to the new module, you cannot access it in the
first module:
Module Module1
Sub Main()
ShowMessage() 'Will not work!
Console.WriteLine("Press Enter to continue...")
Console.ReadLine()
End Sub
End Module
Module Module2
Private Sub ShowMessage()
Console.WriteLine("Hello there!")
End Sub
End Module
In module scope, you can also make variables—not just procedures—public or private; this
example declares strText in the second module using a Dim statement:
Module Module1
Page 72 of 77
Sub Main()
Console.WriteLine(strText) 'Will not work!
Console.WriteLine("Press Enter to continue...")
Console.ReadLine()
End Sub
End Module
Module Module2
End Module
By default, module-level variables are declared Private when you use Dim, so strText cannot be
accessed outside its module. However, if you declare this new variable Public, it can be accessed
in the first module with no problem:
Module Module1
Sub Main()
Console.WriteLine(strText)
Console.WriteLine("Press Enter to continue...")
Console.ReadLine()
End Sub
End Module
Module Module2
Public strText = "Hello there!"
End Module
Namespace Scope
You can also declare elements at namespace level in Visual Basic. A namespace is an OOP
feature used to keep elements with the same name from conflicting with each other in larger
programs. (If you don't use a Namespace statement in your code, all your code is in the same
namespace.) Declaring a module-level element Friend or Public makes it available to all
procedures throughout the namespace.
We now have the background we'll need on procedures and scope, two very important
programming concepts. Next, let's tackle handling the runtime errors that may crop up because
the Visual Basic language puts special emphasis on this topic.
Page 73 of 77
procedure has access to that variable. When the variable’s scope is limited to a procedure it’s
called local.
e.g.
Private Sub Command1_Click()
Dim i as Integer
Dim Sum as Integer
For i=0 to 100 Step 2
Sum = Sum +i
Next
MsgBox “ The Sum is “& Sum
End Sub
A variable whose value is available to all procedures within the same Form or Module are called
Form-wide or Module-wide and can be accessed from within all procedures in a component. In
some situations the entire application must access a certain variable. Such variable must be
declared as Public.
Lifetime of a Variable : It is the period for which they retain their value. Variables declared as
Public exist for the lifetime of the application. Local variables, declared within procedures with
the Dim or Private statement, live as long as the procedure.
You can force a local variable to preserve its value between procedure calls with the Static
keyword. The advantage of using static variables is that they help you minimize the number of
total variables in the application.
Variables declared in a Form outside any procedure take effect when the Form is loaded and
cease to exist when the Form is unloaded. If the Form is loaded again, its variables are
initialized, as if it’s being loaded for the first time.
The time during which a variable retains its value is known as its lifetime. The value of a
variable may change over its lifetime, but it retains some value. When a variable loses scope, it
no longer has a value.
When a procedure begins running, all variables are initialized. A numeric variable is initialized
to zero, a variable-length string is initialized to a zero-length string (""), and a fixed-length string
is filled with the character represented by the ASCII character code 0,
or Chr(0). Variant variables are initialized to Empty. Each element of a user-defined
type variable is initialized as if it were a separate variable.
When you declare an object variable, space is reserved in memory, but its value is set
to Nothing until you assign an object reference to it using the Set statement.
If the value of a variable isn't changed during the running of your code, it retains its initialized
value until it loses scope.
A procedure-level variable declared with the Dim statement retains a value until the procedure is
finished running. If the procedure calls other procedures, the variable retains its value while
those procedures are running as well.
Page 74 of 77
If a procedure-level variable is declared with the Static keyword, the variable retains its value as
long as code is running in any module. When all code has finished running, the variable loses its
scope and its value. Its lifetime is the same as a module-level variable.
A module-level variable differs from a static variable. In a standard module or a class module, it
retains its value until you stop running your code. In a class module, it retains its value as long as
an instance of the class exists. Module-level variables consume memory resources until you reset
their values, so use them only when necessary.
If you include the Static keyword before a Sub or Function statement, the values of all the
procedure-level variables in the procedure are preserved between calls.
1. Start
2. Enter input hours, rate
3. if hours <= 8 then
4. pay = hours * rate
5. else
6. pay = 8 * rate + (hours – 8) * rate * 1.5
7. print pay
8. End
Page 75 of 77
Give your variable names something that matches the data type your using, at first glance of your
code, I would assume "txt2" and "txt3" were TextBox controls.
The easiest way is to assign the result of the calculation to a variable, so you have something
like:
01 Dim dblPay as Double
02 Dim dblHours as Double
03 Dim dblRate as Double
04
05 ' Assign values to your variables
06 dblHours = 2
07 dblRate = 4.5
08
09 ' Do the calculation
10 dblPay = dblHours * dblRate
11
12 ' Print the result - not the use of Cstr to case the Double to a String for printing
13 Print Cstr(dblPay)
Another Example
Have To Write A Pseudo Code For A Unit Converter. It Converts Miles To KM:
Page 76 of 77
1. REM “Number of Animals = NA”
2. REM “Number of Animal Legs = NAL”
3. REM “Number of Pigs = NP”
4. REM “Number of Chicken = NC”
5. NA$=87
6. NAL$=266
7. NC$=0
8. PRINT “Enter Number of Pigs”
9. INPUT NP$
10. NC$=NA$-NP$
11. IF NC$*2+NP$*4==266
12. THEN PRINT “The number of pigs” NP$ “and the number of chickens”
NC “entered are correct”
13. GOTO 17
14. ELSE GOTO 15
15. PRINT “Your input for number of pigs is wrong”
16. GOTO 8
17. END
Figure B
Page 77 of 77