Programming 511
Programming 511
PROGRAMMING 511
YEAR 1 SEMESTER 1
Page | 0
| PROGRAMMING 511
Registered with the Department of Higher Education as a Private Higher Education Institution under the Higher Education Act, 1997.
Registration Certificate No. 2000/HE07/008
LEARNER GUIDE
PREPARED ON BEHALF OF
RICHFIELD GRADUATE INSTITUTEOF TECHNOLOGY (PTY) LTD
Copyright © 2018
Richfield Graduate Institute of Technology (Pty) Ltd
Registration Number: 2000/000757/07
All rights reserved; no part of this publication may be reproduced in any form or by any means, including
photocopying machines, without the written permission of the Institution.
Page | 1
| PROGRAMMING 511
Page | 3
| PROGRAMMING 511
Prescribed textbook:
An Introduction to Programming Visual Basic Using Visual Basic 2012 9th ed. 2013 David .I
Schneider 9780133378504
Page | 4
| PROGRAMMING 511
ONE|PROBLEM SOLVING
LEARNING OUTCOMES
1. Introduction
2. Understand the Program Development Cycle
3. Correlate data in flowcharts
4. Understand the use of Pseudo code and Hierarchy Charts
1.1. Introduction
Hardware refers to the machinery in a computer system (such as the monitor, keyboard,
and CPU) and software refers to a collection of instructions, called a program that
directs the hardware. Programs are written to solve problems or perform tasks on a
computer. Programmers translate the solutions or tasks into a language the computer
can understand. As we write programs, we must keep in mind that the computer will
only do what we instruct it to do. Because of this, we must be very careful and thorough
with our instructions. Note: A program is also known as a project, application, or
solution.
This problem-solving approach is the same as that used to solve word problems in an
algebra class. For example, consider the following algebra problem:
ONE| PROBLEM SOLVING
The first step is to determine the type of answer requested. The answer should be a
number giving the speed in miles per hour (the output). (Speed is also called velocity.)
The information needed to obtain the answer is the distance and time the car has
travelled (the input).
Page | 5
| PROGRAMMING 511
The formula
Speed = Distance/Time
is used to process the distance travelled and the time elapsed in order to determine the
speed. That is,
We determine what we want as output, get the needed input, and process the input to
produce the desired output.
In the following chapters we discuss how to write programs to carry out the preceding
operations. But first we look at the general process of writing programs.
tried to bake with no plan at all. Although it's difficult to imagine an architect building a
bridge or a factory without a detailed plan, many programmers (particularly students in
their first programming course) try to write programs without first making a careful
plan. The more complicated the problem, the more complex the plan may be. You will
spend much less time working on a program if you devise a carefully thought out step-
by-step plan and test it before actually writing the program.
Many programmers plan their programs using a sequence of steps, referred to as the
program development cycle. The following step-by-step process will enable you to use
your time efficiently and help you design error-free programs that produce the desired
output.
Page | 6
| PROGRAMMING 511
3. Choose the interface: Select the objects (text boxes, buttons, etc.).
Determine how the input will be obtained and how the output will be displayed.
Then create objects to receive the input and display the output. Also, create
appropriate buttons and menus to allow the user to control the program.
5. Test and debug: Locate and remove any errors in the program.
Testing is the process of finding errors in a program, and debugging is the process
of correcting errors that are found. (An error in a program is called a bug.) As the
program is typed, Visual Basic points out certain types of program errors. Other
types of errors will be detected by Visual Basic when the program is executed;
however, many errors due to typing mistakes, flaws in the algorithm, or incorrect
use of the Visual Basic language rules can be uncovered and corrected only by
ONE| PROBLEM SOLVING
careful detective work. An example of such an error would be using addition when
multiplication was the proper operation.
6. Complete the documentation: Organize all the material that describes the
program.
Documentation is intended to allow another person, or the programmer at a later
date, to understand the program. Internal documentation (comments) consists of
statements in the program that are not executed, but point out the purposes of
various parts of the program. Documentation might also consist of a detailed
Page | 7
| PROGRAMMING 511
description of what the program does and how to use the program (for instance,
what type of input is expected). For commercial programs, documentation includes
an instruction manual and on-line help.
Page | 9
| PROGRAMMING 511
Flowcharts should "flow" from the top of the page to the bottom. Although the
symbols used in flowcharts are standardized, no standards exist for the amount
of detail required within each symbol.
Example:
Create a flowchart that prompts a user to enter a number. After the number has
been entered, it is displayed.
Page | 10
| PROGRAMMING 511
Pseudo code is an abbreviated plain English version of actual computer code (hence,
pseudo code). The geometric symbols used in flowcharts are replaced by English-like
statements that outline the process. As a result, pseudo code looks more like computer
code than does a flowchart.
Pseudo code allows the programmer to focus on the steps required to solve a problem
rather than on how to use the computer language. The programmer can describe the
algorithm in Visual Basic-like form without being restricted by the rules of Visual Basic.
When the pseudo code is completed, it can be easily translated into the Visual Basic
language.
Examples 1:
Examples2:
Page | 11
| PROGRAMMING 511
Examples 2:
Hierarchy charts depict the organization of a program but omit the specific
processing logic. They describe what each part, or module, of the program does
and they show how the modules relate to each other. The details on how the
modules work, however, are omitted. The chart is read from top to bottom and
ONE| PROBLEM SOLVING
from left to right. Each module may be subdivided into a succession of sub
modules that branch out under it. Typically, after the activities in the succession
of sub modules are carried out, the module to the right of the original module is
considered. A quick glance at the hierarchy chart reveals each task performed in
the program and where it is performed.
Page | 12
| PROGRAMMING 511
SECTION SUMMARY
Hierarchy charts: Show how the different parts of a program relate to each other.
SDLC(System Development Life Cycle).A Software Development Life Cycle is essentially a
series of steps, or phases, that provide a model for the development and lifecycle
management of an application or piece of software.
Algorithm: is a procedure or formula for solving a problem.
Page | 13
| PROGRAMMING 511
1. What does the acronym SDLC mean, and what does an SDLC portray?
2. List five steps of Program Development Cycle or System Development
Life Cyclic (SDLC).
Page | 14
| PROGRAMMING 511
LEARNING OUTCOMES
TWO| FUNDAMENTALS OF PROGRAMMING IN VISUAL BASIC.NET
1. VB.NET Background
2. Integrated Development Environment (IDE) For VB.Net
3. Manipulate controls and change their properties
4. Define VB.Net events
5. Declare number variables, increment variable values.
6. Utilise Built-In Functions : Math.Sqrt, Int, Math.Round
7. Work with string variables
8. Format output with format functions
9. Format Output with Zones
10. Get input form an input dialog box, use a message dialog box for output
11. Use masked text box for input
2.1. Introduction
Like all other .NET languages, VB.NET has complete support for object-oriented
concepts. Everything in VB.NET is an object, including all of the primitive types (Short,
Integer, Long, String, Boolean, etc.) and user defined types, events, and even assemblies.
All objects inherits from the base class Object.
VB.NET is implemented of Microsoft's .NET framework. Therefore, it has full access to all
the libraries in the .Net Framework. It's also possible to run VB.NET programs on Mono,
the open-source alternative to .NET, not only under Windows, but even Linux or Mac
OS.
The following reasons make VB.Net a widely used professional language:
• Modern, general purpose.
• Object oriented.
• Component oriented.
• Easy to learn.
• Structured language.
• It produces efficient programs.
• It can be compiled on a variety of computer platforms.
• Part of .Net Framework.
Page | 15
| PROGRAMMING 511
Visual Basic programs display a Windows-style screen (called a form) with boxes into
which users type (and in which users edit) information and buttons that they click to
initiate actions. The boxes and buttons are referred to as controls. In this section, we
examine forms and four of the most useful Visual Basic controls.
Page | 16
| PROGRAMMING 511
The process for invoking Visual Basic varies slightly with the edition of Visual Basic
installed on the computer. To invoke Visual Basic from a computer that has Visual Basic
Express installed, click the Windows Start button, hover over All Programs, and then
click on Microsoft Visual Basic Express Edition. With the other editions of Visual Basic,
hover over All Programs, hover over Microsoft Visual Studio, and then click on Microsoft
Visual Studio in the short list that is revealed.
Launch your Visual Basic .NET or Visual Studio software. When the software first loads,
you'll see a screen something like this one, if you have the 2010 version:
Page | 17
| PROGRAMMING 511
Figure 2-2
This causes the default names to be incremental. Since a program usually consists of
many controls, it is usually a good idea to rename your controls and give them
TWO| FUNDAMENTALS
meaningful and friendlier names. The name should help you identify what the button is
used for. To change the name of a control, on the Properties window, click the (Name)
field, type the desired name and press Enter.
Page | 18
| PROGRAMMING 511
So a variable is a storage area of the computer's memory. Think of it like this: a variable
is an empty cardboard box. Now, imagine you have a very large room, and in this room
you have a whole lot of empty cardboard boxes. Each empty cardboard box is a single
variable. To add two numbers together, write the first number on a piece of paper and
put the piece of paper into an empty box. Write the second number on a piece of paper
and put this second piece of paper in a different cardboard box.
Now, out of all your thousands of empty cardboard boxes two of them contain pieces of
paper with numbers on them. To help you remember which of the thousands of boxes
hold your numbers, put a sticky label on each of the two boxes. Write "number1" on the
TWO| FUNDAMENTALS OF PROGRAMMING IN VISUAL BASIC.NET
What have we just done? Well, we've created a large memory area (the room and the
cardboard boxes), and we've set up two of the boxes to hold our numbers (two
variables). We've also given each of these variables a name (the sticky labels) so that we
can remember where they are.
That's code from Visual Basic Net. It's VB's way of setting up (or declaring) variables.
Here's a breakdown of the variable Declaration
Dim:
Short for Dimension. It's a type of variable. You declare (or "tell" Visual Basic) that you
are setting up a variable with this word. We'll meet other types of variables later, but for
now just remember to start your variable declarations with Dim.
Page | 19
| PROGRAMMING 511
As Integer
We're telling Visual Basic that the variable is going to be a number (integer). Well meet
alternatives to Integer later.
Number1 = 3
The equals sign is not actually an equals sign. The = sign means assign a value of. In
other words, here is where you put something in your variable. We're telling Visual Basic
to assign a value of 3 to the variable called number1. Think back to the piece of paper
going into the cardboard box. Well, this is the programming equivalent of writing a value
on a piece of paper.
Utilise Built-In Functions : Math.Sqrt, Int, Math.Round
TWO| FUNDAMENTALS OF PROGRAMMING IN VISUAL BASIC.NET
Visual Studio .NET provides an easy way of performing mathematical functions, such as
addition, subtraction, multiplication, division, exponentiation, integer division, and
finding a remainder. For all other tasks, you can utilize the System.Math class. In this tip,
I will look at a simple way of working with math-related functions in VB.NET.
.NET offers common operators to facilitate the basic mathematical functions, such as:
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Exponentiation (^)
Integer Division (\)
Finding the remainder (Mod)
However, for other operations, you can use the methods available in the System.Math
class.
Math.Sqrt takes the square root of a number. With it, you pass one Double value as an
argument, and receive the square root of that as another Double. This method requires
more time to compute fractional square roots
Example
With lstDisplay.Items
.Add (result1)
.Add (result2)
.Add (result3)
.Add (result4)
End with
Page | 20
| PROGRAMMING 511
Output
1
1.4142135623731
1.73205080756888
2
Math.Round
Numbers can be rounded in many ways. In the .NET Framework, Math.Round provides
built-in logic. With it we round with special options—away from zero, or to even.
It acts on many numeric types,including Doubleand Decimal.
TWO| FUNDAMENTALS OF PROGRAMMING IN VISUAL BASIC.NET
Example
Math written on chalkboard
This program calls Math.Round on the Double 123.45. With no options, it rounds this
number to 123. With a second option of 1, we round to one decimal place. This yields
the values 123.5 (for AwayFromZero) and 123.4 (for ToEven).
AwayFromZero:
With a positive number, this option will round up—so 123.45 becomes 123.5.
ToEven:
This will round to an even number—so 123.45 becomes 123.4 because 4 is an even
number and 5 is not.
Page | 21
| PROGRAMMING 511
Example
With lstDisplay.Items
TWO| FUNDAMENTALS OF PROGRAMMING IN VISUAL BASIC.NET
.Add (before)
.Add (after1)
.Add (after2)
.Add (after3)
End with
With lstDisplay.Items
.Add (before)
.Add (after4)
.Add (after5)
End with
Output
123.45
123.5
123.4
123
125.101
125
125.1
Page | 22
| PROGRAMMING 511
SECTION SUMMARY
Page | 23
| PROGRAMMING 511
Boolean Conditions: Condition that yield two condition, either True or False – ( Yes or
No, 1 or 0)
GUI: Graphical User Interface
Variable: is a storage area of the computer's memory.
Dim: Short for Dimension: is a key word of visual basic, that is use to declare a
variable.
Built-in-function: A function is similar to a normal procedure but the main purpose of
the function is to accept a certain input from the user and return a value which is
passed on to the main program to finish the execution.
TWO| GLOSSARY OF TERMS
Page | 24
| PROGRAMMING 511
1. Which controls you can use to accept entry from the user?
2. List any five controls commonly used in VB.NET?
3. Declare two variables of different data type.
4. Declare an integer variable and assign 1900 to it.
dbData = 3.14159
intData = dbData
lblDiplay.Text = dbData
lblDis.Text = intData
TWO| REVIEW QUESTIONS
Page | 25
| PROGRAMMING 511
THREE|GENARAL PROCEDURES
Learning Outcomes
3.1. Introduction
Visual Basic has two devices, Sub procedures and Function procedures that are
used to break complex problems into small problems to be solved one at a time.
To distinguish them from event procedures, Sub and Function procedures are
referred to as general procedures. General procedures also eliminate repetitive
code and can be reused in other programs.
Procedures are an essential part of almost every VB program. When you define a
procedure, whether it's a Function or a Sub procedure, you need to decide
whether the procedure arguments are passed by reference or by value.
3.2. Sub Procedure
A procedure is a group of statements that together perform a task when called.
After the procedure is executed, the control returns to the statement calling the
procedure. VB.Net has two types of procedures:
• Functions
• Sub procedures or Subs
A Sub procedure returns no value. We implement and call this kind of method.
Subs optionally have argument lists and formal parameters. These parameters can
THREE| GENARAL PROCEDURES
A sub procedure is an assignment that is carried but doesn't give back a result. To
create a sub procedure, start by typing the Sub keyword followed by a name (like
everything else, a procedure must have a name). The name of a procedure is
always followed by parentheses. At the end of the sub procedure, you must type
End Sub.
Page | 26
| PROGRAMMING 511
Sub ProcedureName()
End Sub
The name of a procedure should follow the same rules we learned to name the
variables, omitting the prefix. In addition:
If the procedure performs an action that can be represented with a verb, you
can use that verb to name it. Here are examples: show, display
To make the name of a procedure stand, you should start it in uppercase. Examples are
Show, Play, Dispose, Close
You should use explicit names that identify the purpose of the procedure. If a procedure
would be used as a result of another procedure or a control's event, reflect it on the
name of the sub procedure. Examples would be: afterupdate, longbefore.
If the name of a procedure is a combination of words, you should start each word in
uppercase. Examples are: AfterUpdate, SayItLoud
The section between the Sub and the End Sub lines is referred to as the body of the
procedure. Here is an example:
Sub Assignment()
THREE| GENARAL PROCEDURES
End Sub
The body of the procedure is used to define what, and how the, assignment should be
carried. For example, if you need to use a variable, you can declare it and specify the
kind of variable you need. There is no restriction on the type of variables that can be
declared in a procedure. Here is an example in which a string variable is declared in the
body of a sub routine:
Sub Assignment()
Dim strFullName As String
End Sub
In the same way, you can declare as many variables as you need inside of a procedure.
The actions you perform inside of a procedure depend on what you are trying to
Page | 27
| PROGRAMMING 511
accomplish. For example, a procedure can simply be used to create a string. The above
procedure can be changed as follows:
Sub Assignment()
Dim strFullName As String
strFullName="Paul Bertrand
Yamaguchi"
End Sub
User-defined procedures are procedures that you design and write. These are in
contrast to the methods contained in the FCL classes, which are supplies for you. You
create user-defined procedures to give your code structure and organization. In
addition, you can create reusable code by designing procedures that others can invoke.
There are two categories of user-defined procedures: Public or Private.
The declaration of a Sub procedure begins with a Sub statement and the Name of the
procedure followed by a set of ( ). It ends with the End Sub statement. The code that
appears between these two statements is the body of the procedure. When the sub
procedure executes, the code within will execute.
Private SubDisplay_Message( )
‘name of procedure is Display_Message
Code statements
End Sub
THREE| GENARAL PROCEDURES
This type of statement is known as a procedure call. It causes the procedure to execute.
You can also use the Call keyword, which is an optional command.
Call DisplayMessage( )
When a procedure call executes, the application branches to the procedure and
executes the body of the sub procedure. When it has finished, it returns to the location
of the procedural call and resumes executing at the next statement.
Page | 28
| PROGRAMMING 511
Example 1:
The following example demonstrates how to call and define a Sub procedure.
Example
Output:
Hello
Sub procedure
Back To Click Event
A function procedure returns a value to the part of the program that called
the function procedure. Like a Sub procedure, a function procedure is a set
of statements that perform a task when the function is called. Like the Sub
procedure, it is written in the code window and is not attached to any
control. In addition, a function returns a value that can be used in an
expression.
Page | 29
| PROGRAMMING 511
End Function
Similar to a Sub procedure declaration the AccessSpecifier is optional and specifies the
accessibility of the function. If you do not specify an access specifier, the default is
Public.
Next is the keyword Function, followed by the function name. Inside the parenthesis is
an optional list of parameters. Following
the parenthesis is As Datatype. The
datatype listed is the part of the
GOOD PROGRAMMING PRACTICE:
declaration that determines the data type Capitalize the first letter of procedure
of the value returned by the function. name. Alternatively use only uppercase
letters.
An example of a function is:
CALCULATE_SUM = sngResult
End Function
Page | 30
| PROGRAMMING 511
When creating a procedure that will use an external value, declare the argument
that represents that value between the parentheses of the procedure. For a sub
routine, the syntax you use would be:
Sub ProcedureName(Argument)
End Sub
Function Sub
Function Sub
The argument must be declared as a normal variable, omitting only the Dim
keyword. Here is an example that creates a function that takes a string as
argument:
End Sub
A certain procedure can take more than one argument. In this case, in the
parentheses of the procedure, separate the arguments with a comma. Here is an
example of a sub routine that takes two arguments:
Page | 31
| PROGRAMMING 511
In the body of a procedure that takes one or more arguments, use the argument(s) as
you see fit as if they were locally declared variables. For example, you can involve them
with values inside of the procedure. You can also exclusively use the values of the
arguments to perform the assignment.
For the receiving procedure to accept an argument, it must also be equipped with a
parameter located in the ( ). A parameter is a special variable that receives an
argument being passed into the procedure. An example of a Sub procedure that uses a
parameter is:
Page | 32
| PROGRAMMING 511
‘ ‘code within the code window itself; not attached to any control
End Sub
Output result:
Page | 33
| PROGRAMMING 511
When variables of the same name are declared with Dim statements in two different
procedures (either event or Sub), Visual Basic gives the variables separate identities and
treats them as two different variables. A value assigned to a variable in one part of the
program will not affect the value of the likenamed variable in the other part of the
program.
Normally, we place the Dim statement just after the Public Class formName statement
(We refer to this region as the Declarations section of the Code window.) A classlevel
variable is visible to every procedure. When a class-level variable has its value changed
by a procedure, the value persists even after the procedure has finished executing. We
say that such a variable has class-level scope. Variables declared inside a procedure are
said to have local scope.
In general, the scope of a variable is the portion of the program that can refer to it.
Class-level scope also is referred to as module-level scope, and local scope also is
referred to as procedure-level scope. If a procedure declares a local variable with the
same name as a class-level variable, then the name refers to the local variable for code
inside the procedure.
THREE| GENARAL PROCEDURES
Page | 34
| PROGRAMMING 511
UNIT SUMMARY
Page | 35
| PROGRAMMING 511
User-defined procedures are procedures that you design and write. These are in
contrast to the methods contained in the Framework Class Library (FCL) classes.
There are two categories of user-defined procedures: public and private. Private
procedures are you write with in the module to provide services so that objects; private
procedures cannot be invoked by code in other objects. In contrast, public procedures
are procedures you write specifically designed to be invoked by other objects.
The scope of a variable represents its visibility or accessibility and is determined
by where you declare it. A variable declared within a procedure has procedure scope.
However, a variable decaled outside the procedures within a module is accessible to
code within all of the procedures in the module-it has module scope.
Variables can also have what is called block scope. When you write code that is
grouped using an If, Do or For, and terminated with End, Next, and Loop, the code is
called a block. If you declare a variable within such a code block, its scope is limited to
that block.
You create an optional arguments by adding the keyword Optional to a
parameter variable declaration in the procedure header and then indicating a default
value.
Overloading a procedures means you write multiples procedures with the same
name but with different signatures. Overloading is a convenient technique to avoid using
unique names for procedures.
You can overload a function procedure with a Sub procedure and vice versa. The
return data type is not part of a procedure’s signature.
When passing an argument to a procedure, be aware of several different
distinctions that interact with each other:
o Whether the underlying programming element is modifiable or non
modifiable
o Whether the argument itself is modifiable or non modifiable
o Whether the argument is being passed by value or by reference
o Whether the argument data type is a value type or a reference type
THREE| UNIT SUMMARY
Page | 36
| PROGRAMMING 511
Procedure: A group of statements that together perform a task, does not return a value.
Function procedure:A group of statements that together perform a task, return a value
to the part of the program that called the function procedure
Pass-by-Reference: the procedure has access to the original argument and can make
changes to the original argument. The code is ByRef.
Page | 37
| PROGRAMMING 511
UNIT3REVIEW QUESTIONS
*****
*****
13. An integer is said to be prime if it’s divided by only 1 and itself. For example,
2,3,5,7 are prime, but 4,6,8 and 9 are not.
a. Write a function that determine whether a number is prime.
b. Use this function in a program that determine and print all the
prime numbers being 2 and 10, 000. How many of these numbers do you really
have to test before being sure that you’ve found all the primes?
Page | 38
| PROGRAMMING 511
FOUR|DECISION MAKING
4.1. Introduction
Decision making structures require that the programmer specify one or more conditions
to be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other statements to
be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages:
Statement Description
Page | 39
| PROGRAMMING 511
It is the simplest form of control statement, frequently used in decision making and
changing the control flow of the program execution. Syntax for if-then statement is:
If condition Then
[Statement(s)]
End If
If the condition evaluates to true, then the block of code inside the If statement will be
executed. If condition evaluates to false, then the first set of code after the end of the If
statement (after the closing End If) will be executed.
Private SubADD()
'local variable definition
Dim a AsInteger=10
End Sub
FOUR| DECISION MAKING
Page | 40
| PROGRAMMING 511
If the condition is TRUE then the control goes to between IF and Else block, that is the
program will execute the code between IF and ELSE statements.
If the condition is FALSE then the control goes to between ELSE and END IF block, that is
the program will execute the code between ELSE and END IF statements.
FOUR| DECISION MAKING
If you want to check more than one condition at the same time, you can use Else If.
Visual Basic programs display a Windows-style screen (called a form) with boxes into
which users type (and in which users edit) information and buttons that they click to
initiate actions. The boxes and buttons are referred to as controls. In this section, we
examine forms and four of the most useful Visual Basic controls.
Page | 41
| PROGRAMMING 511
Example 1:
1) If the marks is greater than 80 then the student get higher first class
2) If the marks less than 80 and greater than 60 then the student get first class
3) If the marks less than 60 and greater than 40 then the student get second class
4) The last condition is, if the marks less than 40 then the student fail.
Line 2: If total marks greater than 80 show message - "Got Higher First Class”
Line 4: If total marks greater than 60 show message - "Got First Class”
Page | 42
| PROGRAMMING 511
Line 7: If those three conditions failed program go to the next coding block
Example
End If
End Sub
End Class
Page | 43
| PROGRAMMING 511
The three main logical operators are And, Or, and Not. If cond1 and cond2 are
conditions, then the condition.
is true if both cond1 and cond2 are true. Otherwise, it is false. The condition
FOUR| DECISION MAKING
cond1 Or cond2
The difference is that the Select Case control structure basically only make decision on
one expression or dimension (for example the examination grade) while the If ...Else If
Page | 44
| PROGRAMMING 511
statement control structure may evaluate only one expression, each If....Else If
statement may also compute entirely different dimensions. Select Case is preferred
when there exist many different conditions because using If...Then..else If statements
might become too messy.
Different items appearing in the same list must be separated by commas. Each action
consists of one or more statements. After the selector is evaluated, Visual Basic looks for
the first value-list item including the value of the selector and carries out its associated
action. (If the value of the selector appears in two different value lists, only the action
associated with the first value list will be carried out.) If the value of the selector does
FOUR| DECISION MAKING
not appear in any of the value lists and there is no Case Else clause, execution of the
program will continue with the statement following the Select Case block.
Page | 45
| PROGRAMMING 511
Example 2
MULTIMEDIA REFERENCE
www.youtube.com/watch?v=h8uR3zOjwUM
http://www.vbtutor.net/lesson8.html
FOUR| DECISION MAKING
Example
age = CInt(TextBoxAge.Text)
SelectCaseage
CaseIs< 3
MessageBox.Show("You are younger than Chris' niece")
CaseIs> 3
MessageBox.Show("You are older than Chris' niece")
CaseIs= 3
MessageBox.Show("You are 3, the same age as Chris' niece")
End Select
FOUR| DECISION MAKING
GOOD PRACTICE:
There are performance advantages in utilising the SELECT CASE STATEMENT but I
wouldn’t use that as the primary means of using it. Expressions like the IF
Statement and SELECT CASE statement are typically executed in millionths of a
second these days. Not even your most critical of users will notice the difference.
However it is simply much easier to read. You should always, without exception,
try to keep your code as clean and as elegant as possible. Your co-workers will
thank you for it. You will thank yourself for it when you go to look at some old
code. Take pride in your work. Be a good craftsman.
Page | 47
| PROGRAMMING 511
UNIT SUMMARY
decision where there are more than two values of a variable you want to evaluate.
Page | 48
| PROGRAMMING 511
Case> 3
Console.WriteLine(“Fantastic”)
Case< 1
If cscMajor Then Console.WriteLine(“Change Majors”)
Case Else
Console.WriteLine(“Meet With Advisor”)
End Select
7. What is the output of the following code?
If 1 < 2 AndAlso 5 < 6 Then
Console.WriteLine(“True”)
Else
Console.WriteLine(“False”)
End If
Page | 49
| PROGRAMMING 511
FIVE| REPETITION
LEARNING OUTCOMES
5.1. Introduction
There may be a situation when you need to execute a block of code several number of
times. In general, statements are executed sequentially: The first statement in a function
is executed first, followed by the second, and so on. Programming languages provide
various control structures that allow for more complicated execution paths. A loop
statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming
languages.
A loop, one of the most important structures in Visual Basic, is used to repeat a
sequence of statements a number of times. At
each repetition, or pass, the statements act upon
variables whose values are changing.
VB.Net provides following types of loops: Follow the link to watch video on loops:
www.youtube.com/watch?v=LPMRGKXAe-8
• Do Loop. www.youtube.com/watch?v=V7WT5a8slic
• For … Next. www.youtube.com/watch?v=uY01sEPvUlI
5.2. Do Loops
The Do loop repeats a sequence of statements either as long as or until a certain
condition is true. A Do statement precedes the sequence of statements, and a Loop
FIVE| REPETITION
statement follows the sequence of statements. The condition preceded by either the
word "While" or the word "Until", follows the word "Do" or the word "Loop". When
Visual Basic executes a Do loop of the form
Do While condition
statement(s)
Loop
Page | 50
| PROGRAMMING 511
Thinking Point?
What will happen if initial counter is
not initialized?
When we know exactly how many times a loop should be executed, a special type
of loop, called a For... Next loop, can be used. For...Next loops are easy to read
and write, and have features that make them ideal for certain common tasks. The
following code uses a For... Next loop to display a table:
Page | 51
| PROGRAMMING 511
Output
1 1
2 4
3 9
4 16
5 25
Page | 52
| PROGRAMMING 511
While .. End While Loop execute the code body (the source code within While
and End while statements ) until it meets the specified condition. The
expression is evaluated each time the loop is encountered. If the evaluation
result is true, the loop body statements are executed.
While [condition]
[loop body]
End While
Line 3: Each time the Loop execute the message and show
Line 4: Counter increment the value of 1 each time the loop execute
End Class
Page | 53
| PROGRAMMING 511
Topic Activities:
The following activities determines the output displayed when the button is
clicked: Private Sub btnDisplay_Click(...) Handles btnDisplay.Click
lstOutput.Items.Add(n)
'Display a message
Dim num As Double = 4
Dim message As String = ""
Do
Select Case num
Case 1
message = "grammer!"
num = -1
Case 2
message = "re a su"
num = (5 - num) * (3 - num)
Case 3
message = "per
pro" num = 4 -
num Case 4
message = "You a"
FIVE| REPETITION
num = 2 * num - 6
End Select
Page | 54
| PROGRAMMING 511
Topic Activities:
The following activities determines the output displayed when the
button is clicked: Private Sub btnDisplay_Click(...) Handles
btnDisplay.Click
'Display a table of the first 5 numbers and their squares
Dim i As Integer
For i = 1 To 5
lstTable.Items.Add(i & " " & i ^ 2)
Next
1
3
5
7
'Display a message
Dim num As Double = 4
Dim message As String = ""
Do
Select Case num
Case 1
message = "grammer!"
num = -1
Case 2
message = "re a su"
num = (5 - num) * (3 - num)
Case 3
message
FIVE| ACTIVITIES
= "per pro"
num = 4 - num
Case 4
message = "You a"
num = 2 *
num - 6
End Select
Page | 55
| PROGRAMMING 511
SECTION SUMMARY
You use the iteration structure, also called a loop, to execute one or more
statement repeatedly.
Basic iteration logic first tests to see if a loop should terminate. If the loop does
not terminate, the statement in the loop body are executed. Control then returns to the
beginning where once again the test determines whether the loop should terminate.
The loop continues in this manner until the terminating condition occurs.
There are two kinds of loop logic: the pre-test loop and post-test loop. Using pre-
test logic, the terminating condition is checked before the body of the loop is executed.
A post-test loop checks for the terminating condition after the body is executed. When
you use a post-test loop, the statement in the loop are executed at least once regardless
of the terminating condition.
There are two general approaches to controlling the number of times a loop
executes: counter control and sentinel control. Counter-control logic employs a variable
called a counter to counter the number of times the loop has executed. Sentinel-control
logic checks the user input for a specific values and terminates when this values, called a
sentinel, is detected.
You use a counter-controlled loop when you want iterate a specific
predetermined number of times. You employ a sentinel-controlled loop when you do
not know how many value many value are to be input and you use a sentinel value to
indicate there is no more input.
You implement the iteration structure in Visual Basic .NET (VB .NET) using either
the Do statement or the For statement.
The Do statement uses two forms: Do While and Do Until. You indicate the end
of the loop by writing the keyword Loop.
The Do While loop continues to execute as long as an expression is true.
The Do Until loop continues to execute until an expression is true.
You can write either a counter-controlled loop or a senile-controlled loop using
the Do statement. You can also create either a pre-test or a post-test loop.
You use the For Next structure to create counter-controlled pre-test loops only.
Although theoretically possible, you generally do not use For Next to write sentinel-
FIVE| SUMMARY
controlled loops.
Page | 56
| PROGRAMMING 511
sum – = counter
ListBox1.Items.Add(sum)
Next
5. Dim n as Integer
For n=1 to 10
If n>6 then
Exit For
End If
Else
ListBox1.Items.Add ( n)
Next
End If
Next
Page | 57
| PROGRAMMING 511
Do
n += 1
sum += n
ListBox1.Items.Add(n & vbTab & sum)
If n = 100 Then
Exit Do
End If
Loop
End Sub
B. For i=0 to 9
lblDisplay.Text = i
Next
For j=1 to i+3
lblDisplay.Text =j
Next
C. For i=0 to 9
While(j Mod 2<>0)
lblDisplay.Text =j
j+=1
End While
Next
Page | 58
| PROGRAMMING 511
10. Which of the following statements about the while loop is not true?
A. The while loop is a posttest loop.
B. Testing condition is made before each iteration.
C. The while loop statement must terminate with a semi-colon.
11. Write VB.NET code to display the asterisk pattern as shown below:
*****
*****
*****
*****
*****
12. Find error on the following code:
Dim intSub As Integer
While intSub <= 10
lblDsplay.Text =intSub
Wend
13. Write a program that use both For.. Next and While statements to sum a
sequence of
Integers.
14. Write a program that uses Do Until to calculate and print the product of the
odd integer
from 1 to 15.
15. Write VB.NET code to display the asterisk pattern as shown below:
*
**
***
****
*****
16. Rewrite the following loop using Do While.
Dim counter As Integer
For counter = 5 To 1 Step -1
FIVE| REVIEW QUESTIONS
lstDidplay.items.Add(counter)
Next
17. Rewrite the following loop using For Next.
Dim counter As Integer = 1
Do While counter <= 9
lstDidplay.items.Add (counter)
Counter += 3
Loop
18. Rewrite the following loop using Do Until.
Dim counter As Integer = 1
Do While counter <=9
lstDidplay.items.Add (counter)
Counter += 3
Loop
Page | 59
| PROGRAMMING 511
SIX|ARRAYS
LEARNING OUTCOMES
6.1. Introduction
This topic introduces the important topic of data structure – collections of related data
items, arrays. An array stores a fixed-size sequential collection of elements of the same
type. An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.
We refer to these collections of variables as the array variables student() and score().
The numbers inside the parentheses of the individual variables are called subscripts, and
Page | 60
| PROGRAMMING 511
Array variables have the same To learn why arrays are important in
kinds of names as simple programming, for this link.
variables. If arrayName is the http://www.homeandlearn.co.uk/NET/n
ets6p1.html
name of an array variable and n
is an Integer literal, variable, or
expression, then the
declaration statement.
score(1) = 92
assign values to the zeroth and first elements.
The statements
For i As Integer = 0 To 2
lstBox.Items.Add(score(i))
Next
Page | 61
| PROGRAMMING 511
87
92
0
The elements in an array can be stored and accessed by using the index of the
array. The following program demonstrates this:
Sub DISPLAY()
Dim arrNumber (10) As Integer ' n is an array of 11 integers '
Dim intSub, intIndex As Integer' initialize elements of array n '
For intSub = 0 To 10
arrNumber (intSub) = i + 100 ' set element at location i to i + 100
Next i
Page | 62
| PROGRAMMING 511
When the above code is compiled and executed, it produces the following result:
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110
Example
Note that in the above code we did not specify the length of the array so the
compiler will do it for us.
Page | 63
| PROGRAMMING 511
week(0) = "Sunday"
week(1) = "Monday"
In the above statement , we initialize the values to the String Array. week(0) = "Sunday"
means , we initialize the first value of Array as "Sunday" ,
We can access the Arrays elements by providing its numerical index, the above
statement we access the second value from the week Array.
In the following program, we declare an Array "week" capability of seven String values
and assigns the seven values as days in a week. Next step is to retrieve the elements of
the Array using a For loop. For finding the end of an Array we used the Length function
of Array Object.
End Sub
End Class
Page | 64
| PROGRAMMING 511
An array can be resized with Array.Resize < T > Method , that means We make an
array bigger or smaller. Array.Resize < T > Method Changes the number of
elements of a one-dimensional array to the specified new size.
This method should be used with only one dimensional Array. This method
allocates a new array with the specified size, copies elements from the old array
to the new one, and then replaces the old array with the new one.
Array.Resize(sArray, 3)
Array.Resize(sArray, 3)
In the above code we resize the array to 3 elements.
Page | 65
| PROGRAMMING 511
The following program shows how to find a specified value from an Array.
If x.Equals(stringToCheck) Then
MessageBox.Show("Find the string ..." + x)
End If
Next
End Sub
End Class
SIX| ARRAYS
MULTIMEDIA REFERENCE
Page | 66
| PROGRAMMING 511
Visual Basic allows you to declare an array without specifying an upper bound with a
statement of the form Dim arrayName() As varitype
Later, the size of the array can be stipulated with a ReDim statement.
The ReDim statement has one shortcoming: It causes the array to lose its current
contents. That is, it resets all String values to Nothing and resets all numeric values to 0.
This situation can be remedied by following ReDim with the word Preserve. The general
form of a ReDim Preserve statement is
Page | 67
| PROGRAMMING 511
When the above code is compiled and executed, it produces the following result:
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0
array(0) = "0"
array(1) = "1"
array(2) = "2"
array(3) = "3"
Another type of array is a 2 Dimensional array. This holds data in a grid pattern,
rather like a spreadsheet. They look like this:
Page | 68
| PROGRAMMING 511
We still have 4 rows, but now we have 4 columns. The values in the image above
represent the array positions. Before, we only had to worry about positions 0 to 3.
We could then place a value at that position. Now, though, we can have values at
position such as 0, 0, and 2, 1.
Module arrayApl
Sub Main()
' an array with 5 rows and 2 columns
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
' output each array element's value '
For i = 0 To 4
For j = 0 To 1
lblDisplay.Text = lblDisplay.Text ("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
SIX| ARRAYS
Next i
End Sub
End Module
Page | 69
| PROGRAMMING 511
When the above code is compiled and executed, it produces the following result:
Output
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8
To set up a 2-D array in Visual Basic .NET you just add a second number between
the round brackets:
Dim grid(3, 3) As Integer
Again, arrays start counting at 0, so the above declarations means set up an array
with 4 rows and 4 columns.
To store values in the grid, you need both numbers between the round brackets:
grid(0, 0) = 1
This means fill row 0, column 0 with a value of 1. You could type out all your
positions and values like this: (The left number between the round brackets is
always the row number; the right number is always the columns.)
grid(0, 0) = 1
grid(1, 0) = 2
grid(2, 0) = 3
grid(3, 0) = 4
grid(0, 1) = 5
grid(1, 1) = 6
grid(2, 1) = 7
grid(3, 1) = 8
grid(0, 2) = 9
grid(1, 2) = 10
grid(2, 2) = 11
grid(2, 2) = 12
grid(0, 3) = 13
grid(1, 3) = 14
grid(2, 3) = 15
SIX| ARRAYS
grid(3, 3) = 16
Page | 70
| PROGRAMMING 511
Typically, though, 2-D arrays are filled using a double for loop. The following code
just places the numbers 1 to 16 in the same positions as in the example above:
For row = 0 To 3
For col = 0 To 3
Next Col
Next
Notice how the outer loop goes from row = 0 to 3 and the inner loop goes from
col = 0 to 3. This allows you to fill all the rows and columns in the array.
To display all the above values in a listbox, you could have this code:
For row = 0 To 3
For col = 0 To 3
Next
ListBox1.Items.Add (temp)
temp = ""
Next
SIX| ARRAYS
Page | 71
| PROGRAMMING 511
Page | 72
| PROGRAMMING 511
Dim i As Integer
Dim j As Integer
Dim minimum As Integer
Dim swapValue As Integer
Dim upperBound As Integer
Dim lowerBound As Integer
lowerBound = LBound(array)
upperBound = UBound(array)
minimum = i
For j = i + 1 To upperBound
'Search for the smallest remaining item in the array
If array(j) < array(minimum) Then
'A smaller value has been found, remember the
‘position in the array
minimum = j
End If
Next j
End If
Next i
End Sub
Page | 73
| PROGRAMMING 511
SECTION SUMMARY
Page | 74
| PROGRAMMING 511
lstOutput.Items.Add(a(5) + a(10))
lstOutput.Items.Add(a(5 + 10))
ONE| REVIEW QUESTIONS
lstOutput.Items.Add(a(20))
End Sub
Page | 75
| PROGRAMMING 511
An arrays are related by the fact that they have the same________
and______
A(n) _______ should be used to declare the size of an array
An array that uses two subscripts is referred to as a(n)___________
Page | 76