BACS 287 - University of Northern Colorado

Download Report

Transcript BACS 287 - University of Northern Colorado

BACS 287
Programming
Fundamentals 1
BACS 287
Programming Fundamentals

This lecture introduces the following topics:
–
Variables



–
–
State
Scope
Lifetime
Constants
User-Defined Data Structures
BACS 287
Visual Basic Programming




Programs are explicit instructions to the computer
telling it how to solve a problem.
Programs use the structured logic that you create with
pseudocode or flowcharts.
Programs differ from pseudocode in that you must
write your program according to the rules of the
language (syntax). Thus, you must convert your
pseudocode to VB statements.
You can see the full VB reference documentation at:
http://msdn.microsoft.com/en-us/library/2x7h1hfk.aspx
BACS 287
Visual Basic Programming

The general hierarchical structure of a VB
program is as follows:
Highest
–
–
–
–
–
–
–
Solution
Project
Forms & Modules
Procedures (functions & subroutines)
Structures (constructs)
Statements
Variables/Constants/Functions/...
Lowest
BACS 287
Variables




Variables are named memory locations that hold temporary
data values during the execution of a program.
There are 4 key characteristics of variables:
– Name – what it is called
– Type – the kind of data it is designed to hold
– Size – how much memory does it take to store it
– Value – the current value of the variable
When you define a variable you determine its name, type, and
size.
You can determine its value either when you define it or later in
the program.
BACS 287
Memory and Variables
0
6
1
D
2
O
3
G
4
1
5
2
7
4
Name: ANIMAL, Type: string, Size: from 0
for 3, Value: "DOG"
Name: COST, Type: number, Size: from 3
for 4, Value: 1274
CPU/Memory Interaction
Variable Definition

Name: Assigns a name to memory location
–
–
–
–
–
–

Begins with a letter or an _ (underscore)
No periods, dashes, spaces, or special characters allowed
in name (underscore ‘_’ is ok)
If it begins with underscore, it must have at least one
alphabetic character or number
<= 1,023 characters in length
Unique within the variable scope
Cannot be a “reserve word” (like ‘print’, ‘true’,…)
The variable can be defined explicitly by the
programmer or implicitly by Visual Basic. You
should always use the explicit method.
BACS 287
Variable Name Prefixes

There are several naming schemes for variables in
Visual Basic.

A popular This
one uses
3 or 4-letter
prefix before a
is thea“Hungarian
notation”
“camel case” descriptive name. It’s called “Hungarian
notation”

The main prefixes are:
bol – Boolean
lng – Long
byt - Byte
int – Integer
sng – Single
dec - Decimal
sho – Short
dbl – Double
dat – Date
str – String
obj – Object
uint – unsigned integer
BACS 287
Variable Definition

Variables can be define explicitly by using
the DIM statement.
The DIM statement allows you to define the
variable’s name, type, size, and value. For
example:
Dim intClassSize as Integer

Dim sngGPA as Single = 3.21
BACS 287
Variable State

The state of the variable is determined by:
–
–
–

Type
Length
Current value
The state of the variable can change during
the execution of the program.
BACS 287
Variable Definition

Type: Determines what kind of data can be stored in the
variable. These are common VB data types.
–
–
–
–
–
–
–
–
–
–
–
–
Byte - whole numbers (0 - 255) (1 byte)
Short - whole numbers (-32,768 – 32,767) (2 bytes)
Integer - whole numbers ( 4 bytes) (-2,147,483,648 to 2,147,483,647)
Long – big whole numbers (8 bytes) (apx. -9 septillion to +9 septillion)
Single – floating point numbers (4 bytes) (apx. 1.4 X 10 -45 to 3.4 X 10 38)
Double – big floating point numbers (8 bytes)
Decimal - high precision decimal numbers (16 bytes)
String - text information (1 byte per character) (up to apx. 2 billion chars)
Boolean - logical values (True or False) (2 bytes)
Date - date and time information (8 bytes)
Object - any data type (4 bytes) (pointer to object)
User-Defined Type – defined by programmer (built from base types)
BACS 287
Variable Definition

It is best to use the smallest data type that
can hold the anticipated data.

It is best to use one of the integer data types
unless you need decimal values.

It is best to explicitly define a variable’s data
type. Otherwise it will be the object type by
default. You should only use the object type
when necessary.
BACS 287
Variable Definition

Size: The amount of memory used by the variable.
This is fixed by the data type selected (or the data
value entered). For example:
Dim intValue as integer  uses 4 bytes
Dim strName as string = “My Name”  uses 7 bytes
Dim datDate as date = #01/05/2002#  uses 8 bytes
Dim objForm as object = frmMyForm  uses 4 bytes
BACS 287
Variable Definition


Value: The value assigned to the memory location
named by the variable.
You can assign values to variables at the time they are
defined or with an assignment statement later in the
program.
Dim strName as String = “Jay Lightfoot”
-ORDim strName as String
strName = “Jay Lightfoot”

This example assign literal values (i.e., literals) to the
variable.
BACS 287
Variable Definition

You can also assign other variables and
constants to variables.
strName = strProfessor
intClassSize = MAX_CLASS

These examples assume strProfessor and
MAX_CLASS were previously defined and
assigned a value.
BACS 287
Variable Definition Examples
Dim bytAge as byte = 30
Dim sngTorque as single = 124.33
Dim dblMass as double = 1.243342E+12
Dim lngNationalDebt as long = 4842532334000
Dim strAddress as string = “123 W. 10th St.”
Dim datValue as date = #09/14/2003#
Dim blnResident as boolean = true
BACS 287
Special Object Values

Value of “Nothing”
Object variables are initially created with a value of “Nothing”
(unless you specify another value). “Nothing” means no
value and is converted to 0 for number data types and the
empty string for strings.

Null Value
Object variables may be assigned a value of “null”. Null
means that the data is unknown or missing. It is different
from 0 or blank. It is also different from “nothing”.
BACS 287
Variable Scope



The scope of the variable is the range of
program instructions over which the variable
is known, and thus capable of being
manipulated.
A variable is visible within its scope and
invisible outside of it.
In Visual Basic, the scope of a variable is
determined by where it is defined.
BACS 287
Variable Scope


Variables can be declared (defined) at different levels in
Visual Basic. The place they are declared determines the
variable scope. The common levels are:
– Public-Level (Global level)
Highest
– Friend-level
– Form / Module-Level
– Procedure-level
– Block-level
Lowest
Each level has different scoping characteristics.
BACS 287
Variable Scope – Block Level

A “block” is a sub-part of a statement. This statement has 2.
If A = true then
dim B as byte
Sum = Sum + 1
Block
Cnt = Cnt + 1
Else
MsgBox(“Error”, “Input Error”)
EndIf
Block
BACS 287
Variable Scope
PROJECT
Public-Level
Friend-Level
Module-Level
Form2
Form1
Form-Level
Procedure1
Block-Level
Procedure2
Block-Level
Form-Level
Procedure
1
Block-Level
Procedure2
Block-Level
Variable Scope

Block-Level - Only visible inside the code block where it is defined.
Dim or Static - Used to define block-level variables

Procedure-Level - Only visible inside the procedure where it is defined.
Blocks within the procedure can see it also.
Dim or Static - Used to define procedure-level variables

Form-Level - Visible to all procedures within the form. Invisible outside the
form.
Dim - Used to define form-level variables.
BACS 287
Variable Scope

Module-Level - Visible inside the module and invisible outside the module.
Private - Used to define module-level variables. Only in modules.
Private intCount as Integer

Friend-Level - Visible inside the project and invisible outside the project.
Friend - Used to define module-level variables. Only in modules.
Friend sngCount as single

Public-Level (Global) - Visible to the entire project and in other projects
while application is running.
Public - Used to define Public-Level variables. Only in modules.
Public strName as String
BACS 287
Variable Scope
Project
Public X as Integer
Form1
Form2
Dim Y as Integer
Dim Z as Integer
Procedure A
Procedure C
Dim L as Integer
Procedure B
Dim M as Integer
Dim N as Integer
Procedure D
Dim O as Integer
Variable Lifetime




The lifetime (or extent) of the variable is the interval
of time in which the memory storage area is bound
to the variable.
Variables defined locally exist only while the
procedure or block in which they are declared is
executing.
Variables defined as Form-level exist as long as the
form is loaded in memory.
Variables defined as module-level or public exist as
long as the application is executing.
BACS 287
Variable Lifetime

Block-Level – Only exists as long as the lexical block where

Procedure-Level - Only exists as long as the procedure
it is defined is executing. Normally the ‘End’ terminator of the
block indicates the end of the variable lifetime.
where it is defined is executing. Static variables are an
exception to this. They exist as long as the program is
executing. Their scope is the same.

Form-Level – Only exist as long as the form is loaded in
memory.
BACS 287
Variable Lifetime

Module-Level – Exist as long as the program is executing.

Friend-Level - Exist as long as the program is executing.

Public-Level (Global) - Exist as long as the program is
executing.
BACS 287
Variable Conversion



The data type of a variable can be changed while the
program is running.
This is often done to modify a string to a number so
you can do calculations or to take a number and
convert it to a string with special formatting
characters (like $ and commas).
Visual Basic has two main ways to do this:
–
–
Build-in conversion functions – only work in VB
Conversion methods – work in any .NET language
BACS 287
Variable Conversion Functions








CDec(expression) – convert to decimal
CByte(expression) – convert to byte
CChar(expression) – convert to character
CDbl(expression) – convert to double
CSng(expression) – convert to single
CInt(expression) – convert to integer
CStr(expression) – convert to string
CDate(expression) – convert to date/time
Example: strResult = Cstr(123)
strResult = Cstr(2 + 6)
BACS 287
Variable Conversion Methods









Convert.ToDecimal(value) – convert to decimal
Convert.ToByte(value) – convert to byte
Convert.ToChar(value) – convert to character
Convert.ToDouble(value) – convert to double
Convert.ToSingle(value) – convert to single
Convert.ToInt32(value) – convert to 4 byte integer
Convert.ToInt16(value) – convert to 2 byte integer
Convert.ToString(value) – convert to string
Convert.ToDateTime(value) – convert to date/time
Example: strResult = Convert.ToString(123)
BACS 287
Variable Conversion – TryParse

A special method called TryParse exists to
perform conversions with formatting.

This method also returns a value of True or
False; thus, it can be used as the condition of
an IF-Then statement.
Example:
blnResult = Decimal.TryParse(textbox.text, sales)

Options also exist to add formatting
characters to the resulting output.
BACS 287
Constants

A constant is similar to a variable except that
its value cannot be changed once it is set.

This is useful for situations where you have a
value that may change over time (but is static
while the program runs).

It also helps document the program and
improves readability.
BACS 287
Constant Definition

There are 2 types of constants:
–
User defined constants (symbolic)
Public Const PI as Double = 3.141592653
Private Const mdatDUE_DATE as Date = #6/16/99#
– System defined constants (intrinsic)
If vbYes then Print “yes”...
If “red” then color = Color.Red...
BACS 287
Constants



Constants can be defined at all the scope
levels that variables can be.
Constants share the same lifetime rules as
variables.
Good programming practices dictate that all
constants be declared at the module level (or
above).
BACS 287
Constants

Constants often follow these naming conventions:
–
–
–
First character – scope indicator (m for module)
Next 3 characters – date type indicator (int,dec,…)
Rest of name capitalized
Public Const mintMIN_AGE as integer = 18
Const decINTEREST as decimal = 3.22332

The second example is a local constant as would be
defined in a procedure.
BACS 287
User-Define Data Structures



User-Defined data structures allow you to
combine several different types of data into a
single structure.
They are useful when you need a single variable
that records several related pieces of
information.
Use the STRUCTURE statement to declare them.
The definition must be made in a module (i.e.,
not local scope).
BACS 287
User-Define Data Structures
Public Structure StudentInfo
Public SSN as String
Public Name as String
Public EnrollDate as Date
Public CurrentStatus as Byte
Public GPA as single
End Structure
...
Dim stuLocal as StudentInfo
...
If stuLocal.Name = “John Smith” then...
BACS 287
User-Define Data Structure
Public Structure ProjectPack
Public frmInput as form
Public frmCalc as form
Private dbProject as database
End Structure
...
Dim Project1 as ProjectPack
...
Project1.frmCalc = frmMyForm
BACS 287
User-Define Data Structures

You can nest user-defined data types so that one
type can be made up of other user-defined data
types.

You can also include other complex structures
(arrays, objects, ...).

Structures support most of the features of classes
(including methods). Thus, structures can contain
procedures that act upon local data.
BACS 287
User-Define Data Structures
Public Structure Employee
' Public members, accessible throughout declaration region.
Public FirstName As String
Public MiddleName As String
Public LastName As String
' Friend members, accessible anywhere within the same
assembly.
Friend EmployeeNumber As Integer
Friend BusinessPhone As Long
' Private members, accessible only within the structure
itself.
Private HomePhone As Long
Private Salary As Double
Private Bonus As Double
' Procedure member, which can access structure's private
members.
Friend Sub CalculateBonus(ByVal Rate As Single)
Bonus = Salary * CDbl(Rate)
End Sub
End Structure
Review

State
–

Scope
–



Block, procedure, form/module, public
Lifetime
–

Name, type, value, size
Block, procedure, form/module, public
Conversions
Constants
User-defined data structures
BACS 287