41
Chapter 3 Variables, Assignment Statements, and Arithmetic

Chapter 3 Variables, Assignment Statements, and Arithmetic

Embed Size (px)

Citation preview

Page 1: Chapter 3 Variables, Assignment Statements, and Arithmetic

Chapter 3Variables, Assignment Statements,

and Arithmetic

Page 2: Chapter 3 Variables, Assignment Statements, and Arithmetic

Learning Objectives

•Declare and use different types of variables in your project.•Use text boxes for event-driven input and output.•Use a four-step process to write code for event procedures•Write Visual Basic instructions to carry out arithmetic operations.•Describe the hierarchy of operations for arithmetic. •Understand how to store the result of arithmetic operations in variables using assignment statements. •Use comments to explain the purpose of program statements.•Discuss using Visual Basic functions to carry out commonly used operations.•Use command buttons to clear text boxes, print a form with the PrintForm method, and exit the project. •Describe the types of errors that commonly occur in a Visual Basic project and their causes.

Page 3: Chapter 3 Variables, Assignment Statements, and Arithmetic

Variables• Variables are named locations in memory (memory cells) in

which we store data that will change at run time• Variable names in VB:****

– Must begin with letter and can use 0-9 in name– Can’t include period, but can contain an underscore– Can’t be over 255 characters– Not case-sensitive, but suggest using upper and lower case

• Example mnemonic variable names– sngProfit_Margin for Profit margin****– curTaxes for taxes on this price– curAmountDue for sum of price and taxes– curYTDEarnings for year to date earnings

Page 4: Chapter 3 Variables, Assignment Statements, and Arithmetic

Data Types• Two primary types of data: numeric and string

• Numeric data can be used in arithmetic operations

– 3.154 2300 -34 .0000354 are all numeric constants

• String data should not be used in arithmetic

– “Dogs” “123-45-6789” “Dr. Brown” are all string constants

• 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 or False**

Page 5: Chapter 3 Variables, Assignment Statements, and Arithmetic

Data Types (cont)

• 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)

• Long Integers - whole numbers (-2,147,483,648 to 2,147,483,647

• Single - fractional numbers to seven significant digits

• Double - fractional numbers to 15 significant digits

Page 6: Chapter 3 Variables, Assignment Statements, and Arithmetic

Data Types (cont)

• 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 don’t declare the variable as a specific data type, but takes up more memory

Page 7: Chapter 3 Variables, Assignment Statements, and Arithmetic

Variable Prefixes

Variable Type Prefix

String str

Integer int

Long Integer lng

Single sng

Double dbl

Currency cur

Date dtm

Boolean bln

Page 8: Chapter 3 Variables, Assignment Statements, and Arithmetic

Advantages of Coding Prefixes

• Standard allows anyone who reads the code to immediately determine data type of variable

• Words that are normally reserved words can be used, i.e. strPrint

• Different objects can practically same name, i.e lblAge (label), or txtAge (text box)

Page 9: Chapter 3 Variables, Assignment Statements, and Arithmetic

Declaring Variables• Declare ALL variables with the DIM statement ****• General form:

– Dim Variable1 as type1, variable2 as type2, etc.• For example,

– Dim strHerName as String, sngMyValue as Single– Dim curMyIncome as Currency, curPrice as Currency– Dim curAmountDue as Currency

• Two or more variables can be declared with same Dim statement but you must include the variable type

• If you fail to declare a variable after the Option Explicit statement has been entered, an error occurs at Run time

• Use variables rather than objects in processing since all textboxes are strings

Page 10: Chapter 3 Variables, Assignment Statements, and Arithmetic

The Option Explicit Statement• Begin ALL Forms with the Option Explicit

command in the declarations procedure of the general object. This forces all variables to be declared****

You may have to correct variable statements in your test!

• To automatically include Option Explicit, go to the Tools|Options|Editor menu selection and check the box for “Require variable declaration”

Page 11: Chapter 3 Variables, Assignment Statements, and Arithmetic

Event-driven Input

• 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• Use an assignment statement to do this:. : 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

Control property or variable = value, variable, or property• 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

Page 12: Chapter 3 Variables, Assignment Statements, and Arithmetic

Comments

• To explain the purpose of a statement, a comment statement is added

• Any statement beginning with an apostrophe or REM is a comment

• Comments can be added before statements or at the end of statements by using an apostrophe

Page 13: Chapter 3 Variables, Assignment Statements, and Arithmetic

VB Code Box 3-1Code to Input Two Numbers

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.TextEnd Sub

Page 14: Chapter 3 Variables, Assignment Statements, and Arithmetic

Functions

• Function - 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

Page 15: Chapter 3 Variables, Assignment Statements, and Arithmetic

Using Functions (cont)• You can’t 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

Page 16: Chapter 3 Variables, Assignment Statements, and Arithmetic

Commonly Used Conversion Functions

Conversion Function

Purpose

CBool Convert argument to Boolean

CCur Convert argument to Currency

CDate Convert argument to Date

CInt Convert argument to Integer

CSng Convert argument to Single

CDbl Convert argument toDouble

Page 17: Chapter 3 Variables, Assignment Statements, and Arithmetic

Assignment Statements• Must convert strings in text boxes to numeric with

Val function, eg,– curPrice = Val(txtPrice)

• Convert numeric variables to strings before assigning to text box, eg,– txtAmountDue = str(curAmountDue)

• Carry out calculations with assignment statements, eg, – curTaxes = 0.07*Price– curAmountDue = curPrice + curTaxes

Page 18: Chapter 3 Variables, Assignment Statements, and Arithmetic

VB Code Box 3-2 Use Val() Function in Inputting Numbers

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

Page 19: Chapter 3 Variables, Assignment Statements, and Arithmetic

VB Code Box 3-3Code for cmdSum Command Button

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 txtSum.Text = Str(intSum) ’display sum in sum text box End Sub

Page 20: Chapter 3 Variables, Assignment Statements, and Arithmetic

Properties Versus Methods

• The dot notation method is the way properties are set at run time.

• Syntax: object. property= valueE.g. 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.

• Syntax: object.methodE.g. txtFirstNum.SetFocus

• The SetFocus method shifts the cursor to the named text box• Methods can’t be used in assignment statements

Page 21: Chapter 3 Variables, Assignment Statements, and Arithmetic

VB Code Box 3-4Code for cmdClear Command Button

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

Page 22: Chapter 3 Variables, Assignment Statements, and Arithmetic

Using Assignment Statements for Calculations

• 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

Page 23: Chapter 3 Variables, Assignment Statements, and Arithmetic

Arithmetic Operators ****• () for grouping + for addition• ^ for exponentiation - for subtraction• - for negation * for multiplication • / for division• \ for integer division (divisor and dividend

are rounded to 0)• Example 7.1111\1.95= 7\2 =3

• mod for modulus• Example 7.1111\1.95= 7\2 =3 with 1 remainder

Page 24: Chapter 3 Variables, Assignment Statements, and Arithmetic

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

• ****Make sure you know this!!!

Page 25: Chapter 3 Variables, Assignment Statements, and Arithmetic

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

3 1 2 5 4 (order)

• Order1 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

****You will see something like this again!

Page 26: Chapter 3 Variables, Assignment Statements, and Arithmetic

String Operators

• For String Variables the only valid operation is that of combining two strings into one****

• Use + or & to combine them• Example:• strBigday = “Christmas” + “ Day”• strBigday = “Christmas” & “ Day”• Result of above is Christmas Day

Page 27: Chapter 3 Variables, Assignment Statements, and Arithmetic

Symbolic Constants

• We can assign a name to a constant with the Const statement

Syntax:

Const constant name as variable type = value

• Examples Const sngIntRate as Single = 0.07

Const intNumYears as Integer=12

Const sngIntRate as Single=0.07,intNumYears as Integer=12

Page 28: Chapter 3 Variables, Assignment Statements, and Arithmetic

Formatting Data• To display information in a pleasing form, we can use the

Format function:• variable or control = Format(variable, “format expression”)

• Where the format expressions are in quotes and include;– Currency– Fixed– Standard– Percent– Scientific

• Example:txtTaxes.Text = Format(curTaxes, “currency”)

Page 29: Chapter 3 Variables, Assignment Statements, and Arithmetic

Variations of the Format Command

Function Description

FormatCurrency Expression formatted as currency along with currency symbol

FormatDateTime Expression formatted as a date or time

FormatNumber Expression formatted as a number

FormatPercent Expression formatted as a percentage with a trailing % character

Round Rounds a number a specified number of decimal places

Page 30: Chapter 3 Variables, Assignment Statements, and Arithmetic

Print Form, Clearing Entries and Setting Focus

• Create a command button called cmdPrint

• To print the form, use the PrintForm command in the cmdPrint click event

• _________________________________

• Create a command button called cmdClear

• To clear a text boxes, set them equal to the null string “”

• To set the focus to a text box, use the Setfocus method

• For example,

txtCustName.SetFocus sets focus to this textbox

Page 31: Chapter 3 Variables, Assignment Statements, and Arithmetic

Coding the Exit Button and Giving User Ability to Use Control Keys

• Create Exit button called cmdExit• In the click event enter this line of code• END• User can also activate the click event from the

keyboard by using the CTRL Key and underlined letter if the caption has an “&” before the applicable letter

• Example E&xit for the Exit command button

Page 32: Chapter 3 Variables, Assignment Statements, and Arithmetic

Pseudocode to Compute and Output Taxes and Amount Due

Begin Procedure CalculateInput customer nameInput video nameInput video priceTaxes = video price times tax rateAmount due = video price + taxesOutput taxesOutput amount due

End procedure

Page 33: Chapter 3 Variables, Assignment Statements, and Arithmetic

VB Code Box 3-5Code for Calculate Button

Private Sub cmdCalc_Click() ’Declare constant and variables Const sngTaxRate as Single = 0.07 ’Use local tax rate Dim curPrice As Currency, curAmountDue As Currency Dim curTaxes As Currency

Price = CCur(TxtVideoPrice.Text) Taxes = Price * TaxRate ’calculate taxes AmountDue = Price + Taxes ’calculate amount due ’Display taxes and amount due in text boxes as strings txtTaxes.Text = Str(Taxes) txtAmountdue.Text = Str(AmountDue)End Sub

Page 34: Chapter 3 Variables, Assignment Statements, and Arithmetic

VB Code Box 3-6Code to Compute and Display

Taxes and Amount Due

Private Sub cmdCalc_Click() Const sngTaxRate as Single = 0.07 'Use local tax rate Dim curPrice As Currency, curAmountDue As Currency Dim curTaxes As Currency Price = CCur(txtVideoPrice.Text) Taxes = curPrice * sngTaxRate 'Compute taxes curAmountDue = curPrice + curTaxes 'Compute amount due 'Format text boxes as currency txtTaxes.Text = Format(curTaxes, "Currency") txtAmountDue.Text = Format(curAmountDue, "Currency") txtVideoPrice.Text = Format(curPrice, "Currency")End Sub

Page 35: Chapter 3 Variables, Assignment Statements, and Arithmetic

VB Code Box 3-7Code to Clear Entries in

cmdClear Command ButtonPrivate Sub cmdClear_Click() ‘Clear all text boxes txtCustName.Text = "" txtVideoName.Text = "" txtVideoPrice.Text = "" txtTaxes.Text = "" txtAmountDue.Text = "" txtCustName.SetFocus ‘set focus to this text boxEnd Sub

Page 36: Chapter 3 Variables, Assignment Statements, and Arithmetic

Using Other Arithmetic Functions• Other useful functions include

– Abs for absolute value Sqr for square root– FV for future value PV for present value– IRR for internal rate of return Pmt for payment– UCase/LCase to convert to upper/lower case– Len for length of a string– Date for the system date– DateValue for the date corresponding to string argument

• We will use Pmt to compute the monthly payment

– MonPay = Pmt(rate, Nper,-LoanAmt)– Pmt(.08/12,60,-10000) = $256.03

Page 37: Chapter 3 Variables, Assignment Statements, and Arithmetic

Creating a 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

Page 38: Chapter 3 Variables, Assignment Statements, and Arithmetic

The Monthly Payment Form

Page 39: Chapter 3 Variables, Assignment Statements, and Arithmetic

VB Code Box 3-8Code to 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

Page 40: Chapter 3 Variables, Assignment Statements, and Arithmetic

Visual Basic Errors

• **** Most mistakes that happen while using VB are a result of human error - not hardware error

• **** VB will NOT automatically detect and alert you to all errors!!

• Syntax errors: caused by incorrect grammar, vocabulary, or spelling . Also caused by using a keyword. Usually caught as you enter the statement. These are pointed out by VB and are usually easy to find and correct.

Page 41: Chapter 3 Variables, Assignment Statements, and Arithmetic

Visual Basic Errors (con’t)

• Run time errors: errors not caught at entry but which involve an incorrect statement or bad data, eg, dividing by zero. The presence of an error is detected by VB when you run the program, but you still have to find the source of the error. More difficult to correct than syntax errors

• Logic errors: those that are VB does not catch as being “wrong”, but which involve erroneous logic, say, only having a program include 11 months of data instead of 12. These are the hardest to find!

• Debugging is the process of finding and correcting program errors. ****