Sie sind auf Seite 1von 59

Chapter 2

DATA TYPE, VARIABLES AND CONSTANTS

Learning Objectives
2

By the end of this class, students should be able to : Identify the various Visual Basic data types. Use data types in programme. Define local, module and global variable. Use local, module and global variable. Use constant in application.

Variables
3

Variables are named locations in memory (memory

cells) in which we store data that will change at run time.


One value can be stored in a memory cell. If you put a new value in a memory cell, the old value will be destroyed.

Variable names in VB: Are used to identify variables. Are different from the value of a variable. Must begin with letter and can use 0-9 in name. Cant include period, but can contain an underscore. Cant be over 255 characters. Not case-sensitive, but suggest using upper and lower case. Should not be a Visual Basic key word.

Variables (Cont.)
4

Example mnemonic variable names : sngProfitMargin

for Profit margin for taxes on this price for sum of price and taxes for year to date earnings

curTaxes

curAmountDue

curYTDEarnings

Data Types
5

Data types indicates what types of information will be

stored in the allocated memory space.


Two primary types of data: numeric and string (non-

numeric).

Numeric
6

2 categories :

Integer numbers without decimals. e.g : 823 or -4560 Decimals numbers with decimal points. e.g : 8.23 or -400.25
Integers and decimals are stored differently inside

Visual Basic.Net and they are treated differently. e.g : -7 is not same as -7.00

Numeric
7

Numeric data can be used in arithmetic

operations :
3.154 2300

-34
0.0000354

String (non-numeric)
8

Is a non-numeric data consisting of a series

of none or more characters. A string may contain numeric digits, but is never used for calculations. Example :
Dogs
123-45-6789 Dr.

Brown

Data Types (cont.)


9

Numeric data types can be subdivided into specific types:


Currency $55,567.78 Integer 255 Single 567.78 long (Integer) 35,455 Double 567.78129086 Boolean True (-1) or False (0)

Data Types (cont.)


10

String stores ASCII symbols (text) and numbers that are not used in mathematical operations, but rather to provide for the input, output, and manipulation of sets of characters Integers whole numbers (-32,768 to 32,767) Size 2 bytes

Long Integers whole numbers (-2,147,483,648 to 2,147,483,647) Size 4 bytes


Single fractional numbers to seven significant digits - Size 4 bytes

Double fractional numbers to 15 significant digits Size 8 bytes

Data Types (cont.)


11

Currency Use with monetary amounts and up to four digits to the right of the decimal Date Use with dates Boolean Use only when the value of a variable is True or False Variant Variable is assigned this type automatically if you dont declare the variable as a specific data type, but takes up more memory

Variable Prefixes
12

Variable Type String Integer Long Integer Single Double Currency Date Boolean

Prefix str int lng sng dbl cur dtm bln

Advantages of Coding Prefixes


13

Standard allows anyone who reads the code to

immediately determine data type of variable. Words that are normally reserved words can be used.

strPrint

Different objects can practically same name lblAge (label) txtAge (text box)

Declaring Variables
14

Dim (Dimension) statement declares variables by assigning them a

name and data type. Declare ALL variables with the DIM statement General form: Dim <Variable name> as <data type> For example, Dim strHerName as String, sngMyValue as Single Dim curAmountDue as Currency * You can combine variable declarations in one Dim statement, separate by a comma, but you must use the As Data Type clause for each variable. * Example : Dim Total As Integer, Sales As Currency. * If you fail to declare a variable after the Option Explicit statement has been entered, an error occurs at Run time

Option Explicit
15

Begin ALL Forms with the Option Explicit

command in the declarations procedure of the general object.

This forces all variables to be declared.

To automatically include Option Explicit,

go to the Tools|Options|Editor menu selection and check the box for Require variable declaration.

Event-driven Input
16

In VB, we often use event-driven input where data is

transferred from text boxes to variables by an event

The user, not the program controls the sequence of events

An assignment statement gives a variable a value by

setting it equal either to an existing quantity or to a value that can be computed by the program. Syntax of an assignment statement :
Control property or variable = value, variable, or property
Example : Company = Microsoft

Assignment Statement
17

Only variables or controls can be on left of the =

sign statement while the value, variable or property is on the right of the = sign.

Assignment Statement
18

sngPi = 3.141592 sngAlpha = 1 sngAlpha = sngAlpha intN = intN + 1 3 = intN intN +1 = intN intN = "Five"

Comments
19

To explain the purpose of a statement, a comment

statement is added. Any statement beginning with an apostrophe () or REM (Short for remark)is a comment.
Comments can be added before statements or at the

end of statements by using an apostrophe. Example : This program displays the current date or Rem This program displays the current date

Simple Calculator
20

Code for command button


21

Private Sub cmdSum_Click


Declare variables

Dim intFirst as Integer, intSecond as Integer Dim intSum as Integer


Assign values to variables

intFirst = txtFirstNum.Text intSecond = txtSecondNum.Text End Sub

Functions
22

Function: Performs an action and returns a value. an built-in operation that takes one or more more arguments and returns a a single value. A Common form of a function is :
variable=functionname(argument1, argument2 )

Not all functions require arguments such as the Date() function. The VAL() function is very common and is used to convert the Text property from a string to a number, which is assigned to Numeric variable. E.g : intQuantity = Val (txtQuantity.Text)

Using Functions
23

You cant use text boxes to do computations because the default

property, Text, is a string and therefore must be converted to a numeric value before a calculation is performed.

It is necessary to convert the results of the computation that will

appear in another text box to a string value , using the Str() function, otherwise you would be assigning an integer value to it.

Example functions for converting data:


Val() to convert a string to a number Str() to convert a number to a string

Code for Val() function


24

Private Sub cmdSum_Click() Declare variables Dim intFirst as Integer,intSecond as Integer Dim intSum as Integer Assign values to variables as number intFirst = Val(txtFirstNum.Text) intSecond = Val(txtSecondNum.Text) End Sub

VB Code (Sum Button)


25

Private Sub cmdSum_Click() Declare variables Dim intFirst as Integer, intSecond as Integer Dim intSum as Integer Assign values to variables as a number intFirst = Val(txtFirstNum.Text) intSecond = Val(txtSecondNum.Text) intSum = intFirst + intSecond Calculate sum display sum in sum text box txtSum.Text = Str(intSum) End Sub

26

Break Time!!!!

Uji Minda!!
27

Soalan Pertama: Anda menyertai perlumbaan. Anda mengejar dan memotong orang yang kedua. Sekarang Anda ditempat yang ke berapa? Jawapan: Jika jawapan anda tempat yang pertama, sudah tentu jawapan anda salah! Jika anda memotong orang kedua sudah tentu anda mengambil tempatnya, tempat kedua!

Soalan Kedua :

28

Bapa Mary ada seramai lima orang anak gadis: 1. Nana, 2. Nene, 3. Nini, 4. Nono. Apakah nama anak gadisnya yang terakhir?

Namanya Mary

Properties Versus Methods


29

Dot notation is the way properties are set at run time. Syntax:

object.property= value txtSum.Text=Str(intSum)

The same notation is used to invoke a method for a control. Methods define the actions a control can carry out. Methods cant be used in assignment statements. Syntax:

object.method txtFirstNum.SetFocus

The SetFocus method shifts the cursor to the named text box.

VB Code (Clear Button)


30

Private Sub cmdClear_Click() Clear text boxes with empty string txtFirstNum.Text = "" txtSecondNum.Text = "" txtSum.Text = "" Set focus back to first text box txtFirstNum.Setfocus End Sub

Using Assignment Statements for Calculations


31

An expression is a combination of one or more

variables and/or constants with operators. A constant is a quantity that does not change. Operators are symbols used for carrying out processing :

Arithmetic, Comparison, Logical

Arithmetic Operators
32

() for grouping (A+B) ^ for exponentiation Radius ^2 - for negation (subtraction) -Amount * for multiplication 3 * price / for division PayRaise/Months

Arithmetic Operators
33

\ for integer division Divisor, dividend, and quotient are rounded to integers

7.1111\1.95 = 7\2 = 3

mod for modulus Integer remainder of an integer division

7.1111\1.95 = 7\2 = 3 with 1 remainder

+ for addition Price + Taxes - for subtraction Salary - Deductions

Examples of valid Expressions


34

curInterest = curPrincipal * sngIntRate sngArea = 3.14157 * sngRadius ^2 curUnitCost = curTotalCost / intUnit

intCounter = 0
intCounter = intCounter + 1

Hierarchy of Operations
35

1. 2. 3.

4.
5. 6.

7.
8.

Operations within parentheses ( ) Exponentiation (^) Negation (-) Multiplication and division (*,/) Integer division (\) Modulo arithmetic (Mod) Addition and subtraction (+,-) String concatenation (&)

Arithmetic Example
36

3 * (Salary - Taxes)^2 + Bonus/Months

Order 1 Subtract Taxes from Salary 2 Square the result 3 Multiply this result by 3 4 Divide Bonus by Months 5 Subtract result from first expression

Arithmetic Examples
37

Y = 3^2*41*2+3

Y = 37

X = [

X = 6556
sngAverage = 70

sngAverage = ((70 + 80)/2 + 65)/2

String Operators
38

For String Variables the only valid operation is that

of combining two strings into one Use + or & to combine them


strBigday = Christmas + Day strBigday = Christmas & Day

Result of above is Christmas Day

Symbolic Constants
39

We can assign a name to a constant

with the Const statement

Examples
Const Pi As Single = 3.14157 Const sngIntRate As Single = 0.07 Const intNumYears As Integer = 12

Vintage Videos
40

Vintage Input-Process-Output
41

INPUT customer name video name video price PROCESSING taxes = price x tax rate amount due = price + taxes OUTPUT taxes amount due

Pseudocode
42

Begin Procedure Calculate Input customer name Input video name Input video price Taxes = video price times tax rate Amount due = video price + taxes Output taxes Output amount due End procedure

Code for Calculate Button


43

Private Sub cmdCalc_Click() ' declaring variables Const sngTaxRate As Single = 0.07 Dim curPrice As Currency, curAmountDue As Currency Dim curTaxes As Currency ' changing format into currency curPrice = CCur(txtVideoPrice.Text) curTaxes = curPrice * sngTaxRate curAmountDue = curPrice + curTaxes ' changing format into text txtTaxes.Text = Str(curTaxes) txtAmountDue.Text = Str(curAmountDue) End Sub

Conversion Functions
44

Conversion Function CBool


CCur CDate CInt CSng CDbl

Purpose
Convert argument to Boolean Convert argument to Currency Convert argument to Date Convert argument to Integer Convert argument to Single Convert argument toDouble

Formatting Data
45

To display information in a pleasing format, we can use the

Format function: General form : variable or control = Format(variable, format expression) Where the format expressions are in quotes and include; Currency Fixed Standard Percent Scientific E.g : txtTaxes.Text = Format(curTaxes, currency)

Calculate button (Revised)


46

Private Sub cmdCalc_Click() Const sngTaxRate As Single = 0.07 Dim curPrice As Currency Dim curAmountDue As Currency Dim curTaxes As Currency curPrice = CCur(txtVideoPrice.Text) curTaxes = curPrice * sngTaxRate curAmountDue = curPrice + curTaxes txtTaxes.Text = Format(curTaxes, "Currency") txtAmountDue.Text = Format(curAmountDue, "Currency") txtVideoPrice.Text = Format(curPrice, "Currency") End Sub

Format Commands
47

Function
FormatCurrency FormatDateTime FormatNumber FormatPercent

Description
Expression formatted as currency along with currency symbol Expression formatted as a date or time Expression formatted as a number Expression formatted as a percentage with a trailing %

Round

Rounds a number a specified number of decimal places

Code to Clear Entries


48

Private Sub cmdClear_Click() clear all text boxes txtCustName.Text = "" txtVideoName.Text = "" txtVideoPrice.Text = "" txtTaxes.Text = "" txtAmountDue.Text = "" set focus to this text box txtCustName.SetFocus End Sub

Some Visual Basic Functions


49

Abs absolute value


Sqr square root FV future value of an annuity PV present value of an annuity IRR internal rate of return

Some Visual Basic Functions


50

Pmt payment to pay off a loan UCase/Lcase to convert to upper/lower case Len length of a string Date system date DateValue date corresponding to string argument

Some Examples
51

txtAnswer.Text = Abs(-3)

3 txtAnswer.Text 5 txtAnswer.Text VB IS FUN txtAnswer.Text 9 txtAnswer.Text 2

= Sqr(25) = UCase("VB is fun") = Len("VB is fun") = Sqr(Len("four"))

Monthly Payment Calculator


Assume you wanted to determine the monthly payment

necessary to pay off a loan at a given interest rate in some number of months

Use PMT function PMT(rate, nper, pv) where: rate = monthly interest rate nper = number of months pv = negative value of loan amount

52

The Monthly Payment Form

53

Compute Monthly Payment


Private Sub cmdCompute_Click() Declare variables Dim curAmount As Currency, intMonths As Integer Dim sngRate As Single Dim curPayment As Currency Convert variables in text boxes curAmount = CCur(txtAmount.Text) intMonths = CInt(txtMonths.Text) Calculate monthly interest rate sngRate = (CSng(txtRate.Text) / 100) / 12 Calculate payment curPayment = Pmt(sngRate, intMonths, -curAmount) txtPayment.Text = Format(curPayment, "Currency") txtAmount.Text = Format(curAmount, "Currency") End Sub
54

EXERCISE
Create and complete the following calculation

Exercise 1 Simple Calculator

Exercise 2 - Vintage Video


57

Exercise 3 Monthly Payment Calculator

THaNK YoU

Das könnte Ihnen auch gefallen