DFP 4013
VISUAL PROGRAMMING
CHAPTER 3 PROGRAM DESIGN AND CODING
Course Learning Outcome
CLO 1: Explain the different elements of a visual
programming language, architecture, IDE, object-oriented
programming techniques and the concepts as building blocks
to develop correct, coherent programs. (C4, PLO1)
CLO 2: Implement a visual (graphical) user interface and
syntax rules in Visual Basic programs using an integrated
development environment (IDE). (C3, P4, PLO1, PLO2)
CLO 3: Develop a windows application in a team that
separate a program into logical sections: the user interface;
the “business logic” through the use of programming
frameworks, code resources and secure coding techniques.
(P4, A3, PLO2, PLO4, PLO9)
Lesson Learning Outcome
Apply common programming technique in Visual Basic.Net.
Data and Operators: Data types, Variable, Constant,
Operators
Control Structure:
a. Selection Structure
b. Looping Structure
Control Arrays.
Sub Procedures and Function Procedures.
Variable, Data Type & Operators
Data Type
Data Types define the type of data that a variable can
store. The type of a variable determines how much space
it occupies in storage and how the bit pattern stored is
interpreted. VB.Net provides a wide range of data types.
The following examples shows data types available:
Integer variables: Long, Integer, Short, Byte
Floating-point variables: Single, Double
Fixed decimal point variable: Decimal
Boolean variables: True, False
Character variable: Char
Text variable: String
Variable Declaration
Use prefixes for Data Type
when declare variable
Example :
Dim dblTaxrate As Double
dblTaxRate = 0.07875
Default Values for Data Types
Data type Default (Initial) value
All numeric types Zero (0)
Boolean False
Char Binary 0
String or Object Empty
Date 12:00 a.m. on
January 1, 0001
Variable
In programming a variable is a place to
store data (temporary).
A variable has a name and a data type. In
Visual Basic .NET, a variable is declared
using the Dim (short for Dimension)
statement.
Using Variable
Here is the syntax:
Dim varName As varType
varName is the name of your variable. varType is
the data type of the variable. Types include string,
integer, double, boolean, etc.
Eg: To declare an integer named IdNo:
Dim IdNo As Integer
Eg: To assign a value for variable:
Dim varName As varType = "Value"
Scope of Variables
A variable can be either of global or local scope.
A global variable is a variable declared in the
main body of the source code, outside all
functions, while a local variable is one declared
within the body of a function or a block.
Scope of Variables
Variable are declared with this possible level of
scope:
Variable Declaration Rules
Variable MUST be declared prior to the code
where they are used
Variable should be declared first in the
procedure (style convention)
Declaring an initial value of the variable in the
declaration statement is optional.
Constants
A constant is declared by the keyword Const.
After a constant is declared, its value cannot
be changed anywhere in your code.
Example:
Const strTitle As String = “My Application”
Constants
Syntax:
Private Const strTitle As String = “My Application”
Looks like a normal declaration except:
Const used instead of Dim
An initialization value is required
By convention, entire name capitalized with
underscore characters to separate words
Constants Declaration Rules
Following are the rules for declaring constants:
Like variables, constant names must start with a
letter or the underscore character.
Constant names cannot exceed 255 characters.
When declaring a constant inside a procedure, do
not include a modifier.
When declaring a module-level constant, use the
Private modifier. The use of Dim is not allowed.
Post-it Questions
Declare studIdNo and its only can Declare a proc_Number in a
be used in local procedure. private procedure.
Declare suhuNormal = 36.9 in Declare a strTitle = “My
public class/procedure. Application” as constant.
Declare pi = 3.142 as constant that Declare userId=admin as a
can only be use in same module. constant in private procedure.
Operators
Visual Basic comes with many built-in operators that
allow us to manipulate data.
An operator performs a function on one or more
operands.
An operand is one of the inputs (arguments) of an
operator.
For example, we add two variables with the "+"
addition operator like this:
intx + inty = intz
“+” is operator
The two variables (x ,y) are called operands.
Types of Operators
There are different types of operators in Visual Basic :
1. Arithmetic Operators
To perform arithmetic operations that involve calculation of numeric values.
2. Concatenation Operators
Concatenation operators join multiple strings into a single string.
3. Comparison/Relational Operators
To compare operands and returns a logical value based on whether the
comparison is true or false (boolean value).
4. Logical Operators
Logical operators are expressions which return a true or false result over a
conditional expression.
Arithmetic Operators
Operator Use
^ Exponentiation
- Negation
* Multiplication
/ Division
\ Integer Division
Mod Modulus Arithmetic
+ Addition
- Subtraction
Common Arithmetic Operators
Examples of use:
decTotal = decPrice + decTax
decNetPrice = decPrice - decDiscount
dblArea = dblLength * dblWidth
sngAverage = sngTotal / intItems
dblCube = dblSide ^ 3
Special Integer Division Operator
The backslash (\) is used as an integer division
operator
The result is always an integer, created by
discarding any remainder from the division
Example
intResult = 7 \ 2 ‘result is 3
shrHundreds = 157 \ 100 ‘result is 1
Modulus Operator
This operator can be used in place of the
backslash operator to give the remainder of a
division operation
intRemainder = 17 MOD 3 ‘result is 2
Any attempt to use of the \ or MOD operator
to perform integer division by zero causes a
DivideByZeroException runtime error
Operators Precedence
Operator precedence tells us the order in which
operations are performed
Parentheses override the order of precedence
Where precedence is the same, operations occur
from left to right
Operators Precedence
Parenthesis ‘( )’
Exponential (^)
Unary identity and Negation (+, -)
Multiplication and Division (*, /)
Integer Division (\)
Modulus (Mod)
Addition and Subtraction (+, -)
String Concatenation (&)
Relational Operators (< , > , >= , <= , <>)
Logical Operators (AND, OR, NOT)
Concatenation Operators
Concatenate: connect strings together
Concatenation operator: the ampersand (&)
Operator Use
+ String Concatenation
& String Concatenation
Include a space before and after the ‘&’ operator
Numbers after ‘&’ operator are converted to strings
Concatenation Operator
How to concatenate character strings:
Ex. 1: strFName = "Bob"
strLName = "Smith"
strName = strName & strLName
So, variable strName will hold data : Bob Smith
Ex. 2: intX = 1, intY = 2
intResult = intX + intY
strOutput = intX & “+” & intY & “=” & intResult
So, variable strOuput will hold data : 1 + 2 = 3
Comparison/Relational Operators
Operator Use
= Equality
<> Inequality
< Less than
> Greater than
>= Greater than or equal to
<= Less than or equal to
Example:
If intCnt <= intMax Then
intTotal += intCnt ' Same as intTotal = intTotal + intCnt
intCnt += 1 ' Same as intCnt = intCnt + 1
Else
intTotal += intCnt
intCnt -= 1 ' Same as intCnt = intCnt - 1
End If
Logical Operators
Operator Use
Not Negation
And Conjunction
Or Disjunction
NOT Operators
NOT
The Not operator returns True when the condition is False. Otherwise, it
returns False.
Example:
If Not (1 = 2) Then
MessageBox.Show("(1 = 2) is False. So Not False is
True")
End If
Truth Table
If Condition is: Not Condition will be:
True False
False True
AND Operators
AND
The And operator returns True when the conditions of the left and right are True.
Otherwise, it returns False. Both conditions are evaluated before the result is returned.
Example:
If (1 = 1) And (2 = 2) Then
MessageBox.Show("(1 = 1) is True. (2 = 2) is True.
So True And True is True")
End If
Truth Table :
Condition1 Condition2 Condition1 And Condition2
True True True
True False False
False True False
False False False
OR Operators
OR
The Or operator returns True when the condition on either side is True. Otherwise, it
returns False. Both conditions are evaluated before the result is returned.
Example:
If (1 = 1) Or (2 = 2) Then
MessageBox.Show("(1 = 1) is True. (2 = 2) is True.
So True And True is True")
End If
Truth Table :
Condition1 Condition2 Condition1 And Condition2
True True True
True False True
False True True
False False False
Combined Assignment Operators
Often need to change the value in a variable and
assign the result back to that variable
For example: var = var - 5
Subtracts 5 from the value stored in var
Operator Usage Equivalent to Effect
+= x += 2 x=x+2 Add to
-= x -= 5 x=x-5 Subtract from
*= x *= 10 x = x * 10 Multiply by
/= x /= y x=x/y Divide by
\= x \= y x=x\y Int Divide by
&= x &= “.” x = x & “.” Concatenate
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 ‘result = 3
Dim n2 As Integer = (96 / 8) / 4 ‘result = 3
Dim n3 As Integer = 96 / (8 / 4) ‘result = 48
Control Structure
Types of Control Structure
Control structure is enable programmers to control
the order of events in their programs.
There are three types of structure in order to
control the order of events :
Sequence control structure
Selection/Decision control structure
Repetition control structure
There are used to select and repeat various
statements and thereby execute complex
algorithms.
Sequential Control Structure
Built in Visual Basic.Net
The computer executes Visual Basic statements
sequentially.
Example:
Add grade to total total = total + grade
Add 1 to counter counter = counter + grade
Selection / Decision Control Structures
Visual Basic lets you test conditions and perform different
operations depending on the results of that test.
The following illustration shows a decision structure that tests
for a condition being true and takes different actions
depending on whether it is true or false.
If...Then...Else constructions
If...Then...Else constructions let you test for one or more conditions
and run one or more statements depending on each condition. You
can test conditions and take actions in the following ways:
Run one or more statements if a condition is True
Run one or more statements if a condition is False
Run some statements if a condition is True and others if it is False
Test an additional condition if a prior condition is False
The control structure that offers all these possibilities is the
If...Then...Else Statement (Visual Basic).
You can use a single-line version if you have just one test and one
statement to run or if you have a more complex set of conditions and
actions, you can use the multiple-line version.
If...Then...Else constructions
Conditional statements allow us to make logical evaluation in a
single-selection statement.
Syntax:
If condition1 Then
Statement1
End If
[marks>=60]
Example: Assign grade as
Passed
If marks >= 60 then
grade = “Passed” [marks<60]
End If
If...Then...Else constructions
Conditional statements allow us to make logical
evaluation in a double-selection statement
Syntax: Example:
If condition1 Then If marks >= 60 Then
Statement1 grade = “Passed”
Else Else
Statement2 grade = “Failed”
End If End If
Assign grade as [marks<60] [marks>=60] Assign grade as
Failed Passed
Nested If…Then…Else Statement
Conditional statements allow us to make logical evaluations for
multiple conditions.
Syntax:
If condition1 Then
statement1 If condition1 Then
Else
statement1
If condition2 Then
Statement2
ElseIf condition2 Then
Else Statement2
If condition3 Then
Statement3 OR ElseIf condition3 Then
Statement3
Else ElseIf condition4 Then
If condition4 Then Statement4
Statement4 Else
Else
Statement5
Statement5
End If End If
End If
End If
End If
Nested If…Then…Else Statement (Cont…)
Example: Example (using ElseIf keyword):
If marks > 80 Then
grade = ‘A’
Else
If marks > 80 Then
If marks > 60 Then
grade = ‘A’
grade = ‘B’ OR ElseIf marks > 60 Then
Else
grade = ‘B’
If marks > 50 Then
ElseIf marks > 50 Then
grade = ‘C’
grade = ‘C’
Else
ElseIf marks > 40 Then
If marks > 40 Then
grade = ‘D’
grade = ‘D’
Else
Else
grade = ‘F’
grade = ‘F’
End If
End If
End If
End If
End If
Select...Case construction
Runs one of several groups of statements,
depending on the value of an expression.
Select [ Case ] testexpression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
Select...Case construction
Select Case statements are used when we want to
perform different actions for each value of a variable.
Dim mark As Single
Dim status As String
Select Case mark State is a Variable to evaluate
Case Is >= 85 Case can be value or string or
condition
status = "Excellence"
Case Is >= 70
status = "Good"
Case Is >= 60
status = "Above Average"
Case Is >= 50
status = "Average"
Case Else Optional: It catches other
status = "Need to work harder" conditions
End Select Must have End Select
Repetition / Looping Control Structures
Looping structures allow The following illustration shows
you to run one or more a loop structure that runs a set of
lines of code repetitively. statements until a condition
You can repeat the
becomes true.
statements in a loop
structure until a condition
is satisfied with a
specified number of times.
Repetition / Looping Control Structures
There are three types of repetition
control structures:
For…Next
Do…Loop & While…Loop
For…Next Loop Statement
For...Next structure used when you want to repeat
a set of statement or a set number of times.
Syntax :
For counter [ As datatype ] = start To end
[ Step step ]
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]
For…Next Loop Statement
Part Description
counter Required in the For statement. Numeric variable. The control variable for the
loop.
datatype Required if counter is not already declared. Data type of counter.
start Required. Numeric expression. The initial value of counter.
end Required. Numeric expression. The final value of counter.
step Optional. Numeric expression. The amount by which counter is
incremented/decremented each time through the loop. It can be negative or
positive value.
statements Optional. One or more statements between For and Next that run the specified
number of times.
Continue For Optional. Transfers control to the next loop iteration.
Exit For Optional. Transfers control out of the For loop immediately.
Next Required. Terminates the definition of the For loop.
For…Next Loop Statement
Data type
counter
Output:
Dim x As Integer = 0
1
Start value
End value 2
For x = 1 To 4
3
lbNumbers.Items.Add(
4
x)
Next x statement
Nested For…Next Statement
For loops can be nested by Output:
inserting one loop within 1
2
another. However, each loop 3
must have a unique counter 4
5
variable. 1
2
Example:
Dim x as Integer = 0 3
Dim y as Integer = 0 4
5
For x = 1 To 3 1
For y = 1 To 5 2
lstNumbers.Items.Add(y) 3
4
Next y 5
Next x
For…Next Loop Statement
Output: 10
9
Dim x as Integer 8
7
For x = 10 To 1 Step -1 6
5
ListBox1.Items.Add (x) 4
3
2
Next x ‘x will be decrease by 1 1
Do While…Loop Statement
Do...Loop structure used to repeat a block of statements
while a Boolean condition is True OR until the condition
becomes True.
Syntax :
Do { While | Until } condition
[ statements ]
[ Exit Do ]
[ statements ]
Loop
---------------------------------OR------------------------------
Do
[ statements ]
[ Exit Do ]
[ statements ]
Loop { While | Until } condition
Do While…Loop Statement
Term Definition
Do Required. Starts the definition of the Do loop.
While Required unless Until is used. Repeat the loop
until condition is False.
Until Required unless While is used. Repeat the loop
until condition is True.
condition Optional. Boolean expression. If condition is Nothing, Visual
Basic treats it as False.
statements Optional. One or more statements that are repeated while, or
until, condition is True.
Exit Do Optional. Transfers control out of the Do loop.
Loop Required. Terminates the definition of the Do loop.
Do While…Loop Statement
Do While.... Loop (PRE TEST) Do.....While Loop (POST TEST)
Dim index As Integer = 11 Dim index As Integer = 11
Do While index <= 10 Do
index += 1 index += 1
ListBox1.Items.Add (x) ListBox1.Items.Add (x)
Loop Loop While index <= 10
Minimum attempt is zero Minimum attempt is 1
Print : 11
Checking condition at first Checking condition at the end
Control Arrays
Controls Arrays
An array is simply a collection of data items of the
same type. The individual items of an array are
accessed using a numerical index.
All arrays in VB are zero based, meaning, the index of
the first element is zero and they are numbered
sequentially.
You must specify the number of array elements by
indicating the upper bound of the array. The upper
bound is the number that specifies the index of the
last element of the array.
Arrays do not have fixed size in Visual Basic
Arrays Declaration
Similar to declaring variables, an array is declared
with a Dim statement.
The array name is followed by a pair of parentheses
to indicate an array variable.
Array can be a single dimension array or
multidimensional array.
Arrays Declaration
Array – a series of individual variables, all
referenced by the same name
Example:
Dim name(4) As String
Ali (0)
Mamat (1)
Minah (2)
Lim (3)
Muthu (4)
Arrays Declaration
General Form
Private Arrayname(UpperSubscript) As Datatype
Dim ArrayName() As Datatype = {InitialValueList}
Dim ArrayName As Datatype() = {InitialValueList}
Example:
Private category(5) As String
Dim index() As Integer = { 1, 5, 12, 20, 24}
Dim index As Integer() = { 1, 5, 12, 20, 24}
One-Dimensional Arrays
A one-dimensional array is an array that only has one
dimension.
It looks like a row of people at a super market.
The following figure illustrates an example of a typical
one-dimensional array:
Arr
ArrayName Array index/subscript
Lower bound Data/elements
Upper bound
Declare and Initialize values to Array
63
Syntax:
Dim arrayName() as dataType
arrayName = New dataType(){values}
OR
Dim arrayName() as dataType = {values}
OR
Dim arrayName(n) As dataType
arrayName(index) = value
Example :
Dim Test() as Integer 'declaring a array Test Test=New
Integer(){1,3,5,7,9} 'initialize values to array Test
OR
Dim Test() as Integer = {1,3,5} 'declare and initialize values
Examples : Arrays Declaration
Upper bound of subscripts
in the array
Dim student(10) As String
Array name Data type
So, How many number of elements in this array??
Assign value to array
65
Syntax : arrayName(index) = value
Example : student(1) = “Ali"
Index / subscript
Read: "student sub one equals Ali"
Which means that the string “Ali" is being stored at the
second location in the array called student… because
all arrays index begin counting at 0.
Multi-dimensional Arrays
As the name implies, a multi-dimensional array is
an array of arrays.
Such an array has the shape of a grid that has rows
and columns.
Example: Dim item(2, 4) As Integer
Multi-dimensional Arrays
Public Sub RectangularArray()
'Declare the array
Dim rect(5, 5) As Integer
Dim counter As Integer = 1
'Print the content of array
Console.WriteLine("Rectangular array example:")
Console.WriteLine()
For i As Integer = 0 To rect.GetUpperBound(0)
For j As Integer = 0 To rect.GetUpperBound(1)
Console.Write(rect(i, j) & ControlChars.Tab)
counter = counter + 1
Next
Console.WriteLine()
Next
End Sub
Advantages of using Arrays
Variables are the basic storage units for holding
data values during processing.
A problem arises, however, with large collections
of data values for which it is impractical to declare
a separate variable for each of them.
Consider a need to store the names or codes for all
the states. It would require declaring and assigning
values to 50 different variables. Fortunately, there
is a way to handle these large sets of similar data
items through use of arrays.
Additional Info
Creating Arrays in VB.Net:
https://www.tutorialspoint.com/vb.net/vb.net_arrays.htm
Multi Dimensional Arrays:
https://www.homeandlearn.co.uk/NET/nets6p5.html
Arrays in Visual Basic
https
://docs.microsoft.com/en-us/dotnet/visual-basic/program
ming-guide/language-features/arrays
/
Sub Procedures and Function
Procedures
Sub Procedures and Function Procedures
A class is a group of code that can include subs,
functions, and other stuff.
A sub and a function are both subroutines, or sections
of code that can be called in the program.
Sub-procedure and function are blocks of code to
accomplish specific tasks. They are executed when
they are called.
The difference between them is that a function has a
return value and a sub does not.
Sub Procedures
The Sub procedure performs a task and then returns
control to the calling code, but it does not return a value
to the calling code.
Each time the procedure is called, its statements are
executed, starting with the first executable statement after
the Sub statement and ending with the End Sub, Exit Sub,
or Return statement.
By default, it is Public, which means you can call it from
anywhere in your application that has access to the module,
class, or structure in which you defined it. A Sub procedure
can take arguments, such as constants, variables, or
expressions, which are passed to it by the calling code.
Sub Procedures
Syntax
Private Sub ProcedureName( parameters )
//statement(s)
End Sub
Example
Public Sub cmdCalculate( )
Dim intNum1, intNum2, intSum As Integer
intNum1 = 2
intNum2 = 3
intSum = intNum1 + intNum2
lblSum.Text = Str(intSum)
End Sub
Function Procedures
The Function procedure performs a task and then
returns control to the calling code and it’s also
returns a value to the calling code.
Each time the procedure is called, its statements run,
starting with the first executable statement after the
Function statement and ending with the first End
Function, Exit Function, or Return statement.
It is Public by default, which means you can call it
from anywhere in your application that has access to
the module, class, or structure in which you defined it.
A Function procedure can take arguments, such as
constants, variables, or expressions, which are passed
to it by the calling code.
Function Procedures
Syntax
Private Function name_of_function (parameters)
As return_value_data_type
//statement(s)
End Function
Example
Public Function AddNums(numA As Single, numB As
Single) As Single
Dim theTotalValue As Single
theTotalValue = numA + numB
Return theTotalValue
End Function
Passing Arguments by Value and by
Reference
Passing Arguments by Value and by
Reference
In Visual Basic, you can pass an argument to a
procedure by value or by reference. This is known as
the passing mechanism, and it determines whether
the procedure can modify the programming
element underlying the argument in the calling
code.
The procedure declaration determines the passing
mechanism for each parameter by specifying the
ByVal or ByRef keyword.
Choice of Passing Mechanism
Protection: In choosing between the two passing mechanisms,
the most important criterion is the exposure of calling variables to
change. The advantage of passing an argument ByRef is that the
procedure can return a value to the calling code through that
argument. The advantage of passing an argument ByVal is that it
protects a variable from being changed by the procedure.
Performance: Although the passing mechanism can affect the
performance of your code, the difference is usually insignificant.
One exception to this is a value type passed ByVal. In this case,
Visual Basic copies the entire data contents of the argument.
Therefore, for a large value type such as a structure, it can be
more efficient to pass it ByRef.
Choice of Passing Mechanism
Protection: In choosing between the two passing mechanisms,
the most important criterion is the exposure of calling variables to
change. The advantage of passing an argument ByRef is that the
procedure can return a value to the calling code through that
argument. The advantage of passing an argument ByVal is that it
protects a variable from being changed by the procedure.
Performance: Although the passing mechanism can affect the
performance of your code, the difference is usually insignificant.
One exception to this is a value type passed ByVal. In this case,
Visual Basic copies the entire data contents of the argument.
Therefore, for a large value type such as a structure, it can be
more efficient to pass it ByRef.
VB.NET program that shows ByVal and
ByRef
Sub Main()
Dim value As Integer = 1
' The integer value doesn't change here when passed ByVal.
ExampleByVal (value)
Console.WriteLine(value)
' The integer value DOES change when passed ByRef.
ExampleByRef(value)
Console.WriteLine(value)
End Sub
Sub ExampleByVal(ByVal test As Integer)
test = 10
End Sub
Sub ExampleByRef(ByRef test As Integer)
test = 10
End Sub
•Q&A
session
Our class ends
today!!