0% found this document useful (0 votes)
2 views

CSC 112 Course Final New 2023

CSC112 is an introductory course on problem solving with computers, covering topics such as algorithms, pseudocode, and flowchart design. It emphasizes the importance of understanding problem-solving processes and strategies, including defining problems, brainstorming solutions, and evaluating results. The course also introduces the use of programming languages like VB for implementing algorithms and solutions.

Uploaded by

lightomonuku
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CSC 112 Course Final New 2023

CSC112 is an introductory course on problem solving with computers, covering topics such as algorithms, pseudocode, and flowchart design. It emphasizes the importance of understanding problem-solving processes and strategies, including defining problems, brainstorming solutions, and evaluating results. The course also introduces the use of programming languages like VB for implementing algorithms and solutions.

Uploaded by

lightomonuku
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

CSC112: Introduction to Problem Solving with Computers (3 Units)

An introduction to many computer sciences topics relating to problem solving.


Problem solving definition.
Steps involve in problem solving.
Algorithms development.
Simple language design and pseudocode.
Problem statement with algorithms.
Pseudocode and flowchart designs. Flowchating symbol.
Problem solving strategies,
Role of algorithms in problems solving process
Implementation strategy, concept and properties of algorithms
program development , flowchart and algorithm.
Program objects, operations, expression and assignments, conditional stut,
Boolean Expression. Scope of identifiers, life time of variables, arrays.
Translation of algorithms, Pseudocode to VB language. Introduction to VB, Practical Aspects.

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:

1. Know how to represent the information (data) describing the problem.


2. Determine the steps to transform the information from one representation into another.

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

Encapsulation and Abstraction and Complexity Hiding

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.

GENERAL PROBLEM SOLVING TECHNIQUE

Defining Problem Solving


Before we talk about the stages of problem solving, it’s important to have a definition of what it
is. Let’s look at the two roots of problem solving — problems and solutions.

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

What is Problem Solving?


Naturally enough, Problem Solving is about solving problems. And we’ll restrict ourselves to
thinking about mathematical problems here even though Problem Solving in school has a wider
goal.

Problem Solving contributes to mathematics itself and so it is a mathematical process. As such it


is to be found in the Strand of Mathematical Processes along with Logic and Reasoning, and
Communication.

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.

method + answer = solution

Generally, problem solving can be achieved using five steps below:

The Five Steps of General Problem Solving


With that understanding of problem solving, let’s talk about the steps that can get you there. The
five problem solving steps are shown in the chart below:

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.

1. Define the Problem


What are you trying to solve? In addition to getting clear on what the problem is, defining the
problem also establishes a goal for what you want to achieve.
Input: something is wrong or something could be improved.
Output: a clear definition of the opportunity and a goal for fixing it.

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

Input: pick-list of possible solutions; decision-making criteria.


Output: decision of what solution you will implement.

4. Implement the Solution

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.

Input: decision; planning; hard work.


Output: resolution to the problem.

5. Review the Results

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.

Input: resolutions; results of the implementation.


Output: insights; case-studies; bullets on your resume.

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.

Pólya’s Four Stages of Problem Solving


1. Understand and explore the problem;
2. Find a strategy;
3. Use the strategy to solve the problem;
4. Look back and reflect on the solution.

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

STEP 1: Understand the Problem


The first step to solving any problem is to understand the problem that you are trying to solve.
You need to know:
❖ What input data/information is available?
❖ What does it represent?
❖ What format is it in?
❖ Is anything missing?
❖ Do I have everything that I need?
❖ What output information am I trying to produce?
❖ What do I want the result to look like ... text, a picture, a graph?
❖ What am I going to have to compute?

STEP 2: Formulate a Model


Understanding the processing part of the problem is vital. Many problems break down into
smaller problems that require some kind of simple mathematical computations in order to
process the data. A simple example shows if we are to compute the average of the incoming
scores. We need to know formula for computing the average of a bunch of numbers. If the
formula we need does not exist, we need to develop one.

In order to come up with a model, we need to fully understand the information available to us.

STEP 3: Develop an Algorithm


Now that we understand the problem and have formulated a model, it is time to come up with a
precise plan of what we want the computer to do.
An algorithm is a precise sequence of instructions for solving a problem.
To develop an algorithm, we need to represent the instructions in some way that is
understandable to a person who is trying to figure out the steps involved.
Two commonly used representations for an algorithm is by using (1) Pseudocode, or (2) flow
charts.
Pseudocode is a simple and concise sequence of English-like instructions to solve a problem. A
Pseudocode is often used as a way of describing a computer Program.
When learning to write programs, it is important to write Pseudocode because it helps you
clearly understand the problem that you are trying to solve. It also helps you avoid getting
bugged down with syntax details when you write your program later.

Some facts about flow charts and pseudocodes


In CSC101, we learnt that it can be difficult to draw a flowchart neatly, especially when mistakes
are made. Thus,
❖ Pseudocode fits more easily on a page of paper.
Page 7 of 77
❖ Pseudocode can be written in a way that is very close to real program code, making it
easier later to write the program
❖ Pseudocode takes less time to write than drawing a flowchart.
❖ Pseudocode will vary according to whoever writes it. That is, one person’s Pseudocode is
often quite different from that of another person.

Some common control structures in designing pseudocodes include Sequence control,


conditional controls (if- then- else), repetition control (repeat - until), etc.

STEP 4: Write the Program


At this point, most of the hard work has been done. We now have to transform the algorithm into
a set of instructions that can be understood by the computer. Writing a program is often called
coding. So the code (also called source code) is actually the program itself. Processing are less
readable and seems somewhat more mathematical. The source code would vary depending on the
programming language that was used. Learning a programming language may seem difficult at
first, but it will become easier with practice.

STEP 5: Test the Program


Once you have a program written, you need to make sure that it solves the problem that it was
intended to solve and that the solutions are correct. Running a program is the process of telling
the computer to evaluate the compiled instructions. When you run your program, if all is well,
you should see the correct output. It is possible however, that your program works correctly for
some set of data input but not for all. If the output of your program is incorrect, it is possible that
you did not convert your algorithm properly into a proper program. It is also possible that you
did not produce a proper algorithm that handles all situations that could arise. Whatever
happened, such problems with your program are known as bugs. Bugs are problems/errors with
a program that cause it to stop working or produce incorrect or undesirable results. It is also a
good idea to have others test your program because they may think up situations or input data
that you may never have thought of. The process of finding and fixing errors in your code is
called debugging.

STEP 6: Evaluate the Solution


Once your program produces a result that seems correct, you need to re-consider the original
problem and make sure that the answer is formatted into a proper solution to the problem. It is
possible that when you examine your results, you realize that you need additional data to fully
solve the problem. Or, perhaps you need to adjust the results to solve the problem more
efficiently.
It is important to remember that the computer will only do what you told it to do. It is up to you
to interpret the results in a meaningful way and determine whether or not it solves the original
problem. It may be necessary to re-do some of the steps again, perhaps going as far back as step1
again, if data was missing.
These are some of the key steps that you should follow in order to solve problems using
computers.

The Problem Solving Cycle


This six steps can also be reduced to four phases: Understand, Design, Write and Review.
In Understanding, there is need to shake each problem description up and pull it apart; to ask
questions about it and to be sure that they fully comprehend its scope. We get them to ask, “What
if?” questions and to challenge aspects that are unclear.
The collection of sample inputs and expected outputs do not only helps to clarify thinking, but
also provides the beginnings of a test data set that can be used later in the process.
Page 8 of 77
In Design, the emphasis is on looking around to find related problems that they have already
solved, or similar problems with which they are familiar with. Here, the input/output samples can
be used to check for completeness and consistency in the design.

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.

Designing The Algorithm


An algorithm is a general solution of a problem which can be written as a verbal description of a
precise, logical sequence of actions. Cooking recipes, assembly instructions for appliances and
toys, or precise directions to reach a friend's house, are all examples of algorithms. A computer
program is an algorithm expressed in a specific programming language. An algorithm is the key
to developing a successful program.

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

Repeat the following while there is more data:

get data for an individual,

calculate the pay for the individual from the current data,

and, update the cumulative pay disbursed so far,

print the pay for the individual.

After the data is exhausted, print the total pay disbursed.

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

• : repeat a set of steps as long as some condition is True, as seen in:


• while new data repeat the following
...

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

A program written in an algorithmic language must be translated into machine language. A


Utility program translates source programs in algorithmic languages to object programs in
machine language. One instruction in an algorithmic language usually translates to several
machine level instructions. The work of the compiler, the translation process, is called
compilation.

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

Simple Program Design with Pseudocode


Pseudocode is writing an indented outline in some people language such as English. It has added
key words to show the structure of the outline.

Six basic Computer operations


1. A computer can receive information
Computers receive information or input from some source when required, such as a keyboard,
disk, or mouse. Some common commands for input are: INPUT, READ, GET, SCAN, etc. For
example:
Read Student name
or
Get Today's date

2. A computer can put out information


A computer can out put some information to some device, such as a display, printer, or disk.
Some common commands for output are: DISPLAY, PRINT, TYPE, PUT, PAINT, etc. For
example:
Display "end of data"
or
Print pay check

3. A computer can perform arithmetic


Computers were invented to perform arithmetic. If a person does arithmetic for hours at a time,
he/she gets bored and so become creative and produces wrong answers. Computers don't get
bored and so can perform arithmetic and algebraic type of calculations. Some common
commands for arithmetic are: +, -, *, /, MOD, COMPUTE, CALCULATE, etc.
For example:
Bill = Price + Tax

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.

6. A computer can repeat a group of actions


The ability of a computer to execute a group of instructions one or more times makes it
worthwhile to write computer programs. Pseudocode uses the keywords: DOWHILE and
ENDDO for defining the repeating instructions. Some common commands for repeat are:
DOWHILE/ENDDO, WHILE/ENDWHILE, REPEAT/UNTIL, PERFORM, etc. For example:

WHILE there are uncounted students DO


Count the next student
ENDWHILE

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.

The Structure Theorem


It is possible to write any program using only three control structure types. The three basic
control structures are: sequence, selection, and repetition.

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:

IF conditon p is true THEN


statement(s) is in true case
ELSE
statement(s) is in false case
ENDIF
Page 14 of 77
Note that: The ELSE statement list can be empty.

3. Repetition
The repetition control structure is a set of instructions to be repeated while a certain condition is
true. Pseudocode shows repetition as:

DOWHILE condition p is true


statement(s)
ENDDO
or
WHILE condition p is true DO
statement(s)
ENDWHILE

Problem Statement with Algorithm


Some guidelines are used to approach the solution of a great variety of problems, particularly
those presented in computer programming.

The strategy consists of five steps:


1. Read and comprehend the problem statement.
2. Select theoretical concepts that may be applied.
3. Qualitative description of the problem.
4. Formalization of a solution strategy.
5. Test and description of the solution.

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

1. Describe your solution qualitatively (you can start by making a narration.)


2. Make some predictions regarding the expected result based only upon the description you
made. Do not assume anything that is not in your description.
3. Make the required relationships and check that the result comes from the selected
variables. (Keep in mind the measurement units.)
4. Substitute values (with their corresponding signs and units) at the end of your
development of relationships.
5. Transform your description into an algorithm (pseudocode or flowchart). Remember, the
algorithm must ask unknown values, show main results and store (in variables) the results
of relationships and formulas.

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)

Problems, Solutions, and Tools

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.

An Algorithm Development Process


Every problem solution starts with a plan. That plan is called an algorithm.
An algorithm is a plan for solving a problem.

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.

Step 1: Obtain a description of the problem.


Step 2: Analyze the problem.
Step 3: Develop a high-level algorithm.
Page 18 of 77
Step 4: Refine the algorithm by adding more details.
Step 5: Review the algorithm.

Step 1: Obtain a description of the problem.


This step is much more difficult than it appears. In the following discussion, the word client
refers to someone who wants to find a solution to a problem, and the word developer refers to
someone who finds a way to solve the problem. The developer must create an algorithm that will
solve the client's problem.

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.

Step 2: Analyze the problem.


The purpose of this step is to determine both the starting and ending points for solving the
problem. This process is analogous to a mathematician determining what is given and what must
be proven. A good problem description makes it easier to perform this step.

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?

Step 3: Develop a high-level algorithm.


An algorithm is a plan for solving a problem, but plans come in several levels of detail. It's
usually better to start with a high-level algorithm that includes the major part of a solution, but
leaves the details until later. We can use an everyday example to demonstrate a high-level
algorithm.

Problem: I need to send a birthday card to my brother, Michael.

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:

Go to a store that sells greeting cards


Select a card
Purchase a card
Mail the card

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.

Step 4: Refine the algorithm by adding more detail.


A high-level algorithm shows the major steps that need to be followed to solve a problem. Now
we need to add details to these steps, but the details depend on the situation. We have to consider
who (or what) is going to implement the algorithm and how much that person (or thing) already
knows how to do. So, if someone is going to purchase Michael’s birthday card on my behalf, my
instructions have to be adapted to whether or not the person is familiar with the stores as well as
knowing my brother's taste in greeting cards.

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.

Step 5: Review the algorithm.


The following questions are typical of ones that should be asked whenever we review an
algorithm. Asking these questions and seeking their answers is a good way to develop skills that
can be applied to the next problem.

• 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?

For example, consider the following two formulae:

Rectangle area = length * width


Triangle area = 0.5 * base * height

Similarities: Each computes an area as well as multiplies two measurements.


Differences: Different measurements are used. The triangle formula contains 0.5.
Hypothesis: Perhaps every area formula involves multiplying two measurements.

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.

THE ROLE OF ALGORITHMS IN TEACHING PROBLEM SOLVING


For example: A sample of indium bromide weighing 0.100 g reacts with silver nitrate, AgNO3,
giving indium nitrate and 0.159 g of AgBr. Determine the empirical formula of indium bromide.

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.

The Difference between Exercises and Problems

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?

The Role of Algorithms in Working Problems


A common source of difficulty in science is the overload that occurs when the demand on
working memory exceeds its capacity. One solution to this overload is to help the student build
strategies that decrease a task's demand on working memory.
These strategies or techniques are tricks for simplifying problems and schemas for organizing
prior knowledge. To some extent, these strategies are algorithms that automate individual steps
in a problem.
If you have not built algorithms for a problem, such as converting between grams and moles, you
will never solve the problem. There is more to working problems, however, than applying
algorithms in the correct order.

Techniques For Laying Out An Algorithm


Pseudo-code
Flowcharts

Pseudo-Code Statements
Output
Input
Process
Decision
Repetition

Statements are carried out in order


Example: calling up a friend
1) Look up telephone number
2) Enter telephone number
3) Wait for someone to answer

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)

Pseudo-Code: Decision Making


If-then
General form:
if (condition is met) then
statement(s)
Example:
if temperature < 0 then
wear a jacket
If-then-else

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

Pseudo-Code: Repetition (2)


repeat-until
Repeat at least once (check condition after statement(s))

Page 23 of 77
General form:
repeat
statement(s)
until (condition is met)

Example:
repeat
Go up to buffet table
until full

Pseudo-Code: Repetition (3)


while-do
Repeat zero or more times (check condition before statement(s))
General form:
while (condition is met)
statement(s)
Example:
while students ask questions
Answer questions

Pseudo-Code: Fast Food Example


Use pseudo-code to specify 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.

Pseudo-Code: Fast Food Example


Approach counter
if want burger then
order burger
if want fries then
order fries
if want drink then
order drink
Pay cashier

Pseudo-Code: Fast Food Example (Computer)


Approach counter
Output 'Order burger?'
Input order_burger
if order_burger = yes then
order_burger
Output 'Order fries?'
Input order_fries
if order_fries = yes then
order fries

Pseudo-Code: Fast Food Example (Computer 2)


Output 'Order drink?'
Input order_drink
If order_drink = yes then
Page 24 of 77
order drink
Pay cashier

Pseudo-Code: ATM Example


Use pseudo-code to specify 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.

Pseudo-Code: ATM Example


Approach ATM
Repeat
Output 'Select option'
Output '1) Make withdrawal'
Output '2) Make deposit'
Output '3) Show balance'
Output '4) Quit'
Input option

Pseudo-Code: ATM Example (2)

Can you spot the limitations of this algorithm?

Summary Of Pseudo-Code Statements


Statement Purpose
Output Display information
Input Get information
Process Perform an atomic (non-divisible) activity
Decision Choose between different alternatives
Repetition Perform a step multiple times

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.

Connector Symbol - Indicates that the flow continues where a


matching symbol (containing the same letter) has been placed.

Or Symbol
Indicates that the process flow continues in more than two branches.

Summoning Junction Symbol


Indicates a point in the flowchart where multiple branches converge
back into a single process.
Merge Symbol
Indicates a step where two or more sub-lists or sub-processes
become one.
Collate Symbol
Indicates a step that orders information into a standard format.
Sort Symbol
Indicates a step that organizes a list of items into a sequence or sets
based on some pre-determined criteria
Subroutine Symbol - Indicates a sequence of actions that perform a
specific task embedded within a larger process. This sequence of
actions could be described in more detail on a separate flowchart.

Manual Loop Symbol


Indicates a sequence of commands that will continue to repeat until
stopped manually
Loop Limit Symbol
Indicates the point at which a loop should stop.
Delay Symbol
Indicates a delay in the process.
Data Storage or Stored Data Symbol
Indicates a step where data gets stored.
Database Symbol
Indicates a list of information with a standard structure that allows
for searching and sorting
Internal Storage Symbol
Indicates that information was stored in memory during a program,
used in software design flowcharts
Display Symbol
Indicates a step that displays information.
Off Page
Indicates that the process continues off page

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.

Common Problem Solving Strategies are as follows:

1. Guess (this includes guess and check, guess and improve)


2. Act It Out (act it out and use of equipment)
3. Draw (this includes drawing pictures and diagrams)
4. Make a List (this includes making a table)
5. Think (this includes using skills you know already)

An In-Depth Look At Strategies

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

pigs chickens pigs legs chickens’ total difference


legs
60 27 240 54 294 28
50 37 200 74 274 8
40 47 160 94 254 -12
41 46 164 92 256 -10

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.

What Strategies Can Be Used At What Levels

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.

A computer can be used to also solve all the problems.

Implementation Strategy

The implementation of a solution requires planning and execution

The Elements are:

• Step-by-step process or actions for solving the problem


• Communications strategy for notifying stakeholders
Where important or necessary, inform those who care for you and/or will be affected by
the change. Prepare them as necessary about your decision
• Resource identification/allocation
Page 36 of 77
• Timeline for implementation

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.

Whether or not you achieved your goals,


it is important to consider what you have learned from your experience: about
yourself, about what you consider important.

Basic Concepts and Properties of Algorithm


Algorithm is a step by step process to get the solution for a well defined problem.

The basic concepts of algorithms are:


• A tool for solving a well-specified computational problem
• An algorithm is said to be correct if, for every input instance, it halts with the correct output

• Algorithms must be:


➢ Correct: For each input produce an appropriate output
➢ Efficient: run as quickly as possible, and use as little memory as possible –
➢ A tool for solving a well-specified computational problem

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 development is an ongoing systematic process that Extension professionals follow as


they plan, implement and evaluate their educational programs. The process is not confined to a
four-year planning cycle. It can be applied on a small scale to an individual workshop; on a
larger scale to a comprehensive community initiative or to a county or statewide program of
action. The scope may be different but the principles of program development remain the same.

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.

Objects in Visual Basic (Visual Studio 2008)


An object is a structure that contains data and methods that manipulate the data. Almost
everything that you do in Visual Basic is associated with objects. If you are new to object-
oriented programming, the following terms and concepts will help you get started.

Classes and Objects


The words "class" and "object" are used so much in object-oriented programming that it is easy
to confuse the terms. Generally, a class is an abstract representation of something, whereas
an object is a usable example of the thing the class represents. The one exception to this rule is
shared class members, which are usable in both instances of a class and object variables declared
as the type of the class.

Fields, Properties, Methods, and Events


Classes consist of fields, properties, methods, and events. Fields and properties represent
information that an object contains. Fields are like variables because they can be read or set
directly. For example, if you have an object named "Car" you could store its color in a field
named "Color."

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, Inheritance, and Polymorphism


Fields, properties, methods, and events are only one half of the object-oriented programming
equation. True object-oriented programming requires objects to support three qualities:
encapsulation, inheritance, and polymorphism.

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.

Overloading, Overriding, and Shadowing


Overloading, overriding, and shadowing are similar concepts that can be easy to confuse.
Although all three techniques enable you to create members with the same name, there are some
important differences.
• Overloaded members are used to provide different versions of a property or method that
have the same name, but that accept different number of parameters, or parameters with
different data types.
• Overridden properties and methods are used to replace an inherited property or method
that is not appropriate in a derived class. Overridden members must accept the same data
type and number of arguments. Derived classes inherit overridden members.
• Shadowed members are used to locally replace a member that has broader scope. Any
type can shadow any other type. For example, you can declare a property that shadows an
inherited method with the same name. Shadowed members cannot be inherited.

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.

We have several types of operators:


• Arithmetic operators
• Boolean operators
• Relational operators
• Bitwise operators

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

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

Here we assign a number to the x variable.


x=x+1
Console.WriteLine(x)

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

The following is a table of arithmetic operators in Visual Basic.

Symbol Name
+ Addition
- Subtraction
* Multiplication
/ Division
\ Integer Division
Mod Modulo
^ Exponentiation

The following example shows arithmetic operations.


Option Strict On

Module Example
Dim a As Byte
Dim b As Byte
Dim c As Byte

Dim add As Byte


Dim sb As Byte
Dim mult As Byte
Dim div 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

Output of the example.

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

We use floating point data types.

c=5/2
Console.WriteLine(c)

This is the 'normal' division operation. It returns 2.5, as expected.

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.

Finally, we will mention exponentiation operator.

Console.WriteLine(9 ^ 2) ' Prints 81

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

Boolean operators are used to work with truth values.

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

a = (True And True)


b = (True And False)
c = (False And True)
d = (False And False)

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

a = (True Xor True)


b = (True Xor False)
c = (False Xor True)
d = (False Xor False)

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

The logical Or operator evaluates to True, if either of the operands is True.

Option Strict On

Module Example

Sub Main()

Dim a As Boolean = True Or True


Dim b As Boolean = True Or False
Dim c As Boolean = False Or True
Dim d As Boolean = False Or False

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

Relational operators are also called comparison operators.

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

Console.WriteLine("six" = "six") ' Prints True


' Console.WriteLine("a" > 6) this would throw
' an exception
Console.WriteLine("a" < "b") ' Prints True

End Sub

End Module

We can compare string objects too. Comparison operators in a string context compare the sorting
order of the characters.

Console.WriteLine("a" < "b") ' Prints True

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

Console.WriteLine("a" < "b")

Console.WriteLine("a is: {0}", Asc("a"))


Console.WriteLine("b is: {0}", Asc("b"))

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

In fact, we compare two numbers, 97 with 98.

Console.WriteLine("ab" > "aa") ' Prints True

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

Dim o1 As Object = New Object


Dim o2 As Object = New Object
Dim o3 As Object

o3 = o2

Console.WriteLine(o1 Is o2)
Console.WriteLine(o3 Is o2)

End Sub

End Module

We create three objects and compare them with the Is operator.

Dim o1 As Object = New Object


Dim o2 As Object = New Object

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 bitwise negation operator changes each 1 to 0 and 0 to 1.

Console.WriteLine(Not 7) ' Prints -8


Console.WriteLine(Not -8) ' Prints 7

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.

Console.WriteLine(6 And 3) ' Prints 2


Console.WriteLine(3 And 6) ' Prints 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 result is 00110 or decimal 7.

Console.WriteLine(6 Or 3) ' Prints 7


Console.WriteLine(3 Or 6) ' Prints 7

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

The result is 00101 or decimal 5.

Console.WriteLine(6 Xor 3) ' Prints 5

Operator precedence

The operator precedence tells us which operators are evaluated first. The precedence level is
necessary to avoid ambiguity in expressions.

What is the outcome of the following expression, 28 or 40?

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)

Console.WriteLine(Not True Or True)


Console.WriteLine(Not (True Or True))

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.

Console.WriteLine(Not True Or True)

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.

On the other hand, the assignment operator is 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.

The compound assignment operators are right to left associated.

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.

Operators and Expressions in Visual Basic : Visual Studio 2015

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.

Operator Precedence in Visual Basic


When several operations occur in an expression, each part is evaluated and resolved in a
predetermined order called operator precedence.
Precedence Rules
When expressions contain operators from more than one category, they are evaluated according
to the following rules:
• The arithmetic and concatenation operators have the order of precedence described in the
following section, and all have greater precedence than the comparison, logical, and
bitwise operators.
• All comparison operators have equal precedence, and all have greater precedence than
the logical and bitwise operators, but lower precedence than the arithmetic and
concatenation operators.
• The logical and bitwise operators have the order of precedence described in the following
section, and all have lower precedence than the arithmetic, concatenation, and
comparison operators.
• Operators with equal precedence are evaluated left to right in the order in which they
appear in the expression.
Precedence Order
Operators are evaluated in the following order of precedence:
Await Operator
Await
Arithmetic and Concatenation Operators
Exponentiation (^)
Unary identity and negation (+, –)
Multiplication and floating-point division (*, /)
Integer division (\)

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.

Overriding Precedence and Associativity


You can use parentheses to force some parts of an expression to be evaluated before others. This
can override both the order of precedence and the left associativity. Visual Basic always
performs operations that are enclosed in parentheses before those outside. However, within
parentheses, it maintains ordinary precedence and associativity, unless you use parentheses
within the parentheses. The following example illustrates this.
Dim a, b, c, d, e, f, g As Double
a = 8.0
b = 3.0
c = 4.0
d = 2.0
e = 1.0
f=a-b+c/d*e
' The preceding line sets f to 7.0. Because of natural operator
' precedence and associativity, it is exactly equivalent to the
' following line.
f = (a - b) + ((c / d) * e)
' The following line overrides the natural operator precedence
Page 55 of 77
' and left associativity.
g = (a - (b + c)) / (d * e)
' The preceding line sets g to 0.5.

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.

Data Types in Assignment Statements


In addition to numeric values, the assignment operator can also assign String values, as the
following example illustrates.
VB
Dim a, b As String
a = "String variable assignment"
b = "Con" & "cat" & "enation"
' The preceding statement assigns the value "Concatenation" to b.

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.

Compound Assignment Statements


Compound assignment statements first perform an operation on an expression before assigning it
to a programming element. The following example illustrates one of these operators, +=, which
increments the value of the variable on the left side of the operator by the value of the expression
on the right.
VB
n += 1
The preceding example adds 1 to the value of n, and then stores that new value in n. It is a
shorthand equivalent of the following statement:
VB
n=n+1
A variety of compound assignment operations can be performed using operators of this type.
The concatenation assignment operator (&=) is useful for adding a string to the end of already
existing strings, as the following example illustrates.
VB

Page 56 of 77
Dim q As String = "Sample "
q &= "String"
' q now contains "Sample String".

Type Conversions in Assignment Statements


The value you assign to a variable, property, or array element must be of a data type appropriate
to that destination element. In general, you should try to generate a value of the same data type as
that of the destination element. However, some types can be converted to other types during
assignment.

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.

Statements in Visual Basic (Continue next week)


A statement in Visual Basic is a complete instruction. It can contain keywords, operators,
variables, constants, and expressions. Each statement belongs to one of the following categories:
• Declaration Statements, which name a variable, constant, or procedure, and can also
specify a data type.
• Executable Statements, which initiate actions. These statements can call a method or
function, and they can loop or branch through blocks of code. Executable statements
include Assignment Statements, which assign a value or expression to a variable or
constant.
This topic describes each category. Also, this topic describes how to combine multiple
statements on a single line and how to continue a statement over multiple lines.
Declaration Statements
You use declaration statements to name and define procedures, variables, properties, arrays, and
constants. When you declare a programming element, you can also define its data type, access
level, and scope.
The following example contains three declarations.
VB
Public Sub applyFormat()
Const limit As Integer = 33
Dim thisWidget As New widget
' Insert code to implement the procedure.
End Sub
The first declaration is the Sub statement. Together with its matching End Sub statement, it
declares a procedure named applyFormat. It also specifies that applyFormat is Public, which
means that any code that can refer to it can call it.
The second declaration is the Const statement, which declares the constant limit, specifying
the Integer data type and a value of 33.
The third declaration is the Dim statement, which declares the variable thisWidget. The data type
is a specific object, namely an object created from the Widget class. You can declare a variable
to be of any elementary data type or of any object type that is exposed in the application you are
using.

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.

Eligible Programming Elements


The programming element on the left side of the assignment operator must be able to accept and
store a value. This means it must be a variable or property that is not ReadOnly, or it must be an
array element. In the context of an assignment statement, such an element is sometimes called
an lvalue, for "left value."
The value on the right side of the assignment operator is generated by an expression, which can
consist of any combination of literals, constants, variables, properties, array elements, other
expressions, or function calls. The following example illustrates this.
VB
x = y + z + findResult(3)
The preceding example adds the value held in variable y to the value held in variable z, and then
adds the value returned by the call to function findResult. The total value of this expression is
then stored in variable x.
Compound Assignment Statements
Compound assignment statements first perform an operation on an expression before assigning it
to a programming element. The following example illustrates one of these operators, +=, which
increments the value of the variable on the left side of the operator by the value of the expression
on the right.
VB
Page 58 of 77
n += 1
The preceding example adds 1 to the value of n, and then stores that new value in n. It is a
shorthand equivalent of the following statement:
VB
n=n+1
A variety of compound assignment operations can be performed using operators of this type.

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.

Checking Compilation Errors


If, after you type a line of code, the line is displayed with a wavy blue underline (an error
message may appear as well), there is a syntax error in the statement. You must find out what is
wrong with the statement (by looking in the task list, or hovering over the error with the mouse
pointer and reading the error message) and correct it. Until you have fixed all syntax errors in
your code, your program will fail to compile correctly.

Term Definition

Assignment Operators Provides links to language reference pages covering


assignment operators such as =, *=, and &=.

Operators and Expressions Shows how to combine elements with operators to


yield new values.

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.

How to: Label Statements Shows how to label a line of code.

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.

Comparison Operators Combined with Logical Operators


Comparison expressions can be combined using logical operators to produce more complex
Boolean expressions. The following example demonstrates the use of comparison operators in
conjunction with a logical operator.
x > y And x < 1000

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.Net is an object-oriented programming language. In Object-Oriented Programming


methodology, a program consists of various objects that interact with each other by means of
actions. The actions that an object may take are called methods. Objects of the same kind are
said to have the same type or, more often, are said to be in the same class.

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.

When we consider a VB.Net program, it can be defined as a collection of objects that


communicate via invoking each other's methods. Let us now briefly look into what do class,
object, methods and instance variables mean.

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

• Class - A class can be defined as a template/blueprint that describes the behaviors/states


that objects of its type support.

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.

A Rectangle Class in VB.Net


For example, let us consider a Rectangle object. It has attributes like length and width.
Depending upon the design, it may need ways for accepting the values of these attributes,
calculating area and displaying details.

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

Public Function GetArea() As Double


GetArea = length * width
End Function
Public Sub Display()
Console.WriteLine("Length: {0}", length)
Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())

End Sub

Shared Sub Main()


Dim r As New Rectangle()
r.Acceptdetails()
r.Display()
Console.ReadLine()
End Sub
End Class
Page 61 of 77
When the above code is compiled and executed, it produces the following result:

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.

• It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; :


" ' / and \. However, an underscore ( _ ) can be used.

• It should not be a reserved keyword.

VB.Net Keywords
The following table lists the VB.Net reserved keywords:

AddHandler AddressOf Alias And AndAlso As Boolean

ByRef Byte ByVal Call Case Catch CBool

CByte CChar CDate CDec CDbl Char CInt

Class CLng CObj Const Continue CSByte CShort

CSng CStr CType CUInt CULng CUShort Date

Decimal Declare Default Delegate Dim DirectCast Do

Double Each Else ElseIf End End If Enum

Erase Error Event Exit False Finally For

Friend Function Get GetType GetXML Global GoTo

Namespace

Handles If Implements Imports In Inherits Integer


Interface Is IsNot Let Lib Like Long
Loop Me Mod Module MustInherit MustOverride MyBase
MyClass Namespace Narrowing New Next Not Nothing
Not Not Object Of On Operator Option

Page 62 of 77
Inheritable Overridable

Optional Or OrElse Overloads Overridable Overrides ParamArray


Partial Private Property Protected Public RaiseEvent ReadOnly
ReDim REM Remove Resume Return SByte Select

Handler

Set Shadows Shared Short Single Static Step


Stop String Structure Sub SyncLock Then Throw
To True Try TryCast TypeOf

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.

Public Sub MyFirstMethod( )


Dim CoffeeBreaks As Integer
' ...
End Sub

Public Sub MySecondMethod( )


Dim CoffeeBreaks As Long
' ...
End Sub

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

Scope in Visual Basic


The scope of a declared element is the set of all code that can refer to it without qualifying its
name or making it available through an Imports Statement (.NET Namespace and Type). An
element can have scope at one of the following levels:
Level Description
Block scope Available only within the code block in which it is declared
Procedure Available to all code within the procedure in which it is declared
scope
Module scope Available to all code within the module, class, or structure in which it is
declared

Scope (Nest class Begins)


These levels of scope progress from the narrowest (block) to the widest (namespace),
where narrowest scope means the smallest set of code that can refer to the element without
qualification. For more information, see "Levels of Scope" on this page.
Specifying Scope and Defining Variables
You specify the scope of an element when you declare it. The scope can depend on the following
factors:
• The region (block, procedure, module, class, or structure) in which you declare the
element
• The namespace containing the element's declaration
• The access level you declare for the element
Use care when you define variables with the same name but different scope, because doing so
can lead to unexpected results. For more information, see References to Declared Elements.
Levels of Scope
A programming element is available throughout the region in which you declare it. All code in
the same region can refer to the element without qualifying its name.

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.

Advantages of Local Variables


Local variables are a good choice for any kind of temporary calculation, for the following
reasons:
• Name Conflict Avoidance. Local variable names are not susceptible to conflict. For
example, you can create several different procedures containing a variable
called intTemp. As long as each intTemp is declared as a local variable, each procedure
recognizes only its own version of intTemp. Any one procedure can alter the value in its
local intTemp without affecting intTemp variables in other procedures.
• Memory Consumption. Local variables consume memory only while their procedure is
running. Their memory is released when the procedure returns to the calling code. By
contrast, Shared and Static variables consume memory resources until your application
stops running, so use them only when necessary. Instance variables consume memory
while their instance continues to exist, which makes them less efficient than local
variables, but potentially more efficient than Shared or Static variables.

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.

Scope at Block or Procedure Level


To make a variable visible only within a block
• Place the Dim Statement for the variable between the initiating and terminating
declaration statements of that block, for example between the For and Next statements of
a For loop.
You can refer to the variable only from within the block.
To make a variable visible only within a procedure
• Place the Dim statement for the variable inside the procedure but outside any block (such
as a With...End With block).
You can refer to the variable only from within the procedure, including inside any block
contained in the procedure.

Scope at Module or Namespace Level


For convenience, the single term module level applies equally to modules, classes, and
structures. The access level of a module level variable determines its scope. The namespace that
contains the module, class, or structure also influences the scope.
To make a variable visible throughout a module, class, or structure
1. Place the Dim statement for the variable inside the module, class, or structure, but outside
any procedure.
2. Include the Private keyword in the Dim statement.
3. You can refer to the variable from anywhere within the module, class, or structure, but
not from outside it.

To make a variable visible throughout a namespace


1. Place the Dim statement for the variable inside the module, class, or structure, but outside
any procedure.
2. Include the Friend or Public keyword in the Dim statement.
3. You can refer to the variable from anywhere within the namespace containing the
module, class, or structure.

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.

Lifetime in Visual Basic


The lifetime of a declared element is the period of time during which it is available for use.
Variables are the only elements that have lifetime. For this purpose, the compiler treats
procedure parameters and function returns as special cases of variables. The lifetime of a
variable represents the period of time during which it can hold a value. Its value can change over
its lifetime, but it always holds some value.
Different Lifetimes
A member variable (declared at module level, outside any procedure) typically has the same
lifetime as the element in which it is declared. A nonshared variable declared in a class or
structure exists as a separate copy for each instance of the class or structure in which it is
declared. Each such variable has the same lifetime as its instance. However, a Shared variable
has only a single lifetime, which lasts for the entire time your application is running.
A local variable (declared inside a procedure) exists only while the procedure in which it is
declared is running. This applies also to that procedure's parameters and to any function return.
However, if that procedure calls other procedures, the local variables retain their values while the
called procedures are running.
Beginning of Lifetime
A local variable's lifetime begins when control enters the procedure in which it is declared. Every
local variable is initialized to the default value for its data type as soon as the procedure begins
running. When the procedure encounters a Dim statement that specifies initial values, it sets
those variables to those values, even if your code had already assigned other values to them.
Each member of a structure variable is initialized as if it were a separate variable. Similarly, each
element of an array variable is initialized individually.
Variables declared within a block inside a procedure (such as a For loop) are initialized on entry
to the procedure. These initializations take effect whether or not your code ever executes the
block.
End of Lifetime
When a procedure terminates, the values of its local variables are not preserved, and Visual
Basic reclaims their memory. The next time you call the procedure, all its local variables are
created afresh and reinitialized.
When an instance of a class or structure terminates, its nonshared variables lose their memory
and their values. Each new instance of the class or structure creates and reinitializes its
nonshared variables. However, Shared variables are preserved until your application stops
running.
Extension of Lifetime
If you declare a local variable with the Static keyword, its lifetime is longer than the execution
time of its procedure. The following table shows how the procedure declaration determines how
long a Static variable exists.
Page 68 of 77
Static variable
Procedure location and sharing Static variable lifetime begins
lifetime ends
In a module (shared by default) The first time the procedure is When your application
called stops running
In a class, Shared (procedure is not The first time the procedure is When your application
an instance member) called either on a specific instance stops running
or on the class or structure name
itself
In an instance of a class, The first time the procedure is When the instance is
not Shared(procedure is an instance called on the specific instance released for garbage
member) collection (GC)
Static Variables of the Same Name
You can declare static variables with the same name in more than one procedure. If you do this,
the Visual Basic compiler considers each such variable to be a separate element. The
initialization of one of these variables does not affect the values of the others. The same applies
if you define a procedure with a set of overloads and declare a static variable with the same name
in each overload.
Containing Elements for Static Variables
You can declare a static local variable within a class, that is, inside a procedure in that class.
However, you cannot declare a static local variable within a structure, either as a structure
member or as a local variable of a procedure within that structure.
Example
Description
The following example declares a variable with the Static keyword. (Note that you do not need
the Dim keyword when the Dim Statement uses a modifier such as Static.)
Code
VB
Function runningTotal(ByVal num As Integer) As Integer
Static applesSold As Integer
applesSold = applesSold + num
Return applesSold
End Function
Comments
In the preceding example, the variable applesSold continues to exist after the
procedure runningTotal returns to the calling code. The next time runningTotal is
called, applesSold retains its previously calculated value.
If applesSold had been declared without using Static, the previous accumulated values would not
be preserved across calls to runningTotal. The next time runningTotal was
called, applesSold would have been recreated and initialized to 0, and runningTotal would have
simply returned the same value with which it was called.
Compiling the Code
You can initialize the value of a static local variable as part of its declaration. If you declare an
array to be Static, you can initialize its rank (number of dimensions), the length of each
dimension, and the values of the individual elements.
Security
In the preceding example, you can produce the same lifetime by declaring applesSold at module
level. If you changed the scope of a variable this way, however, the procedure would no longer

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

Console.WriteLine(strText) 'Will not work!


Console.WriteLine("Press Enter to continue...")
Console.ReadLine()
End Sub

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

Dim strText = "Hello there!"

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.

Variable’s Scope and Lifetime of a Variable


A Variable’s Scope : The scope of a variable is the section of the application that can see and
manipulate the variable. If a variable is declared within a procedure, only the code in the specific

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.

Understanding the Lifetime of Variables: Office 2007

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.

Convert Pseudo Code To Visual Basic


how to convert this pseudo code to visual basic?

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

01 Private Sub cmd1_Click()


02 Dim txt2 As Integer
03 Dim txt3 As Double
04
05 If txt2 > 8 Then
06 Print "txt2 * txt3"
07 Else
08 If txt2 < 8 Then
09 Print "(txt2 * txt3) + (txt2 - 8) * (txt2 * txt3) * 1.5"
10 Print pay
11 End If
12 End Sub
13
14 Private Sub cmd2_Click()
15 End
16 End Sub
17
18 Private Sub Text2_Click()
19
20 End Sub
21
22 Private Sub Text3_Click()
23
24 End Sub
25
26 Private Sub Text4_Click()
27
28 End Sub

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.

1 Dim dblHours As Double

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:

Dim DataIn As Single


Dim DataOut As Single
Dim ConversionType As String
Const M2KCoefficient As Single = 1.6
Private Sub UserForm_Activate()
Call ResetParameters
End Sub
(continue from A)
Sub ResetParameters()
'set the default conversion type
ConversionType = "km2miles"\
OptionButton1.Value = True
ElseIf OptionButton2.Value = True Then
UserForm1.Caption = "Unit Convertor"
ConversionType = "miles2km"
End Sub
End If
Private Sub CommandButton1_Click()
End Sub
Call ReadData
Sub ProcessData()
Call DetermineConversionType
Select Case ConversionType Case "miles2km"
Call ProcessData
DataOut = DataIn * M2KCoefficient
Call OutputData
Case "km2miles"
End Sub
DataOut = DataIn / M2KCoefficient
Sub ReadData()
End Select
DataIn = Val(Txt_imput.Text)
End Sub
End Sub
Sub OutputData()
Sub DetermineConversionType()
Lbl_output.Caption = DataOut
If OptionButton1.Value = True Then
End Sub
(continue to A)

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

You might also like