Beruflich Dokumente
Kultur Dokumente
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
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
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
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
operations :
3.154 2300
-34
0.0000354
String (non-numeric)
8
of none or more characters. A string may contain numeric digits, but is never used for calculations. Example :
Dogs
123-45-6789 Dr.
Brown
Currency $55,567.78 Integer 255 Single 567.78 long (Integer) 35,455 Double 567.78129086 Boolean True (-1) or False (0)
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
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
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
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
go to the Tools|Options|Editor menu selection and check the box for Require variable declaration.
Event-driven Input
16
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
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
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
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
property, Text, is a string and therefore must be converted to a numeric value before a calculation is performed.
appear in another text box to a string value , using the Str() function, otherwise you would be assigning an integer value to it.
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
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
Dot notation is the way properties are set at run time. Syntax:
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.
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
variables and/or constants with operators. A constant is a quantity that does not change. Operators are symbols used for carrying out processing :
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
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
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
String Operators
38
Symbolic Constants
39
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
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
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
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)
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
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
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)
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
53
EXERCISE
Create and complete the following calculation
THaNK YoU