Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3 Part 11 Variables, Constants, and Calculations Chapter 3 Section 3.3 Chapter 3 Section 3.4.

Similar presentations


Presentation on theme: "Chapter 3 Part 11 Variables, Constants, and Calculations Chapter 3 Section 3.3 Chapter 3 Section 3.4."— Presentation transcript:

1 Chapter 3 Part 11 Variables, Constants, and Calculations Chapter 3 Section 3.3 Chapter 3 Section 3.4

2 Chapter 3 Part 12 Section 3.3 Variables Constants

3 Chapter 3 Part 13 So far… Take user input, perform calculation, and display output. Have not stored input or output for future processes within the application.

4 Chapter 3 Part 14 Variable What is it? Storage location in memory (RAM) What does it store? Data during execution of the program What are the uses? Copy and store user input Manipulate user input Store intermediate calculation results to be used later Store results to display for output

5 Chapter 3 Part 15 Why is it called a “variable”? The data may change during execution of the program. The data varies. Run the program several times to calculate different employees’ gross pay.

6 Chapter 3 Part 16 Variable Declaration Statement that sets aside memory; creates the variable location. Specify variable name and data type Syntax: Dim typeVariableName As DataType Examples: Dim intAge As Integer Dim strName As String Declaration before usage of variable

7 Chapter 3 Part 17 Variable Name Rules (Required) 1 st character must be a letter or underscore (not a numeric value) Other characters may be letters, numeric digits, and underscores No spaces allowed No use of keywords as variable names Dim Integer Private

8 Chapter 3 Part 18 Variable Names (Conventions) Descriptive (not vague) names Camel Casing (Uppercase first letter each word chained) dblSalesTax strFirstName intMaximumCapacity Three-letter prefix abbreviation of data type Casing different to distinguish constant & variables.

9 Chapter 3 Part 19 Variable Name Exercise NameValid?Conventional? Quantity strCompany decpayrate Sub Minimum Amt

10 Chapter 3 Part 110 Data Type Indicates the type of data that the variable can store. Important: Specifies amount of memory used Dictates how the variable formats and stores data in memory

11 Chapter 3 Part 111 Data Types Numeric Data Only numbers Available to use in mathematical calculations e.g., 34.56 amount of money e.g., 231 number of available hotel rooms String Data Any symbol Not available for calculations e.g., ISYS 1200 (course number)

12 Chapter 3 Part 112 “Numeric” Data 9.35Weight in tons of crate 125000Population of City 109.95Dollar Amount 84097Zip Code 629111111Social Security Number 8018638843Phone Number If data will NEVER used in calculations (e.g., Phone Number), make it a string.

13 Chapter 3 Part 113 Zip/Postal Code 84097 84097-0555 K1Z 8R7 (Ottawa, Ontario, Canada)

14 Chapter 3 Part 114 Visual Basic.NET Data Types (p. 118) Integer Decimal Double String Boolean

15 Chapter 3 Part 115 Mini Quiz: Which data type… Stores only whole numbers? Decimal, Double, or Long Stores larger numbers? Decimal or Double More appropriate for U.S. Zip Codes? Short, Long, String Provides greater precision? Decimal or Double

16 Chapter 3 Part 116 Default Values Default value created when you declare a variable Numeric (integer, decimal, double, etc.) Assign 0 as default value String Special value known as Nothing Boolean False

17 Chapter 3 Part 117 Variable Initialization Process of specifying an initial value upon declaration Syntax: Dim variableName As DataType = initialValue Example Dim intUnitsSold As Integer = 12 Using a string variable without initialization halts the execution. Dim strName As String = “”

18 Chapter 3 Part 118 Variable Assignment Specifies contents for a variable name. Syntax: variablename = expression Examples: decSalary = val(txtSalary.Text) decSalary = decSalary + decRAISE

19 Chapter 3 Part 119 Constant or Variable Permanent number or string throughout application that does not change or Able to take on different numbers or strings during run time?

20 Chapter 3 Part 120 Constants Read-only data items whose values do not change while the program is running. Declared & set at the beginning of application and maintain their values. Examples: UVSCstring literal constant 0.0625 numeric literal constant decSALESTAXsymbolic constant

21 Chapter 3 Part 121 String Literal Constants Begins and ends with quotation marks. Occurs in pairs. Examples: “314 North State” “Visual Basic” “Utah Valley State College” lblData.Text = "ISYS 1200 class rocks!"

22 Chapter 3 Part 122 Numeric Literal Constants Numeric value that does not change during the operation of the program. Example: lblResult.Text = Val(txtSubtotal.Text) * 0.0625 But…the above statement uses a magic number to display the constant 0.0625.

23 Chapter 3 Part 123 Magic Numbers When a literal constant number is used in an expression. (e.g., 0.0625 in previous slide) Problems: Not immediately apparent to anyone but original programmer what 0.0625 is Maintenance nightmare if use the magic number throughout a complex program and the value changes Sales tax rate changes from 6.25% to 6.6% Nightmare to ensure that you made all changes

24 Chapter 3 Part 124 Magic Numbers, Continued Solution: Create a named constant (a descriptive name) for the literal numeric constant value Use the named constant in expressions Example: Const decRAISE As Decimal = 1000 decSalary = decSalary + decRAISE Declaration: Set up memory and specify its permanent value Must initialize upon declaration (not optional)

25 Chapter 3 Part 125 Magic Numbers, Continued Exceptions: -1, 0, 1 when used as counters (such as in loops)

26 Chapter 3 Part 126 Constant Name Rules Letters and digits First character must be letter No spaces or punctuation marks No reserved (keywords) used Sub If End

27 Chapter 3 Part 127 Constant Name Conventions Use meaningful, descriptive names. Use all CAPITAL letters for symbolic constant names. Include underscore between words. Include three-letter lowercase prefix for data type identification. Examples: strCOLLEGE_NAME decSALES_TAX_RATE

28 Chapter 3 Part 128 Run Time 1) Creates empty table of symbolic constants. 2) Adds row to the table showing the name and value of new constants. 3) Goes to table to look up value corresponding with symbolic name. 4) Substitutes literal value for the name. 5) Executes statement using literal value.

29 Chapter 3 Part 129 Errors Will Result If: You do not assign a value to a symbolic constant declaration. The program contains event procedures that attempt to change a constant’s contents.

30 Chapter 3 Part 130 Intrinsic Constants System-defined constants Typically declared in system class libraries and are available for use in VB programs Examples: MessageBoxIcon.Question ContentAlignment.Left

31 Chapter 3 Part 131 Scope & Lifetime Scope Area of program (such as an event procedure) where the variable is visible and may be accessed by programming statements. Lifetime Time during which the variable exists in memory.

32 Chapter 3 Part 132 Scope Issues Variables can not be used before being declared. See problem example on p. 121 Variables declared inside a procedure are visible only within that procedure. No other procedure can access that variable. See problem example on pp. 121-122 You cannot have multiple variables of the same name in the same procedure.

33 Chapter 3 Part 133 Local and Module Declarations Local Specific (event) procedure only No other procedure can access variables in another procedure* Module (or Class-Level) Available for any procedure on the form Declaration area at top of code window (below programmer ID info); not Form Load though *Can be passed through procedure calls and function calls. See Chapter 6.

34 Chapter 3 Part 134 Lifetime Variable set up and memory reserved upon declaration. Variable exists in memory. Variable destroyed; ends it lifetime. Local variables lifetime expires at the end of the event procedure. Class-level variables lifetime expires when the form is removed from memory.

35 Chapter 3 Part 135 Date Data Types Read pp. 122-123 on your own.

36 Chapter 3 Part 136 Implicit Type Conversion VB attempts to convert data type into data type for specific variable Example: Dim intCount As Integer intCount = txtData.Text ‘user enters 12.2 VB converts 12.2 to 12 Rounds to nearest whole number

37 Chapter 3 Part 137 Conversion Concerns Data entered in text boxes is really a string, but VB tries to convert to numeric data for numeric data types. Type Mismatch or Type Conversion Error intCount = txtData.Text ‘type abc123 Run-time error because VB can’t convert “abc” to integer value.

38 Chapter 3 Part 138 Val Function Converts strings to numeric values. Prevents Type Mismatch and Type Conversion errors. Intrinsic function that carries out specialized operation and returns a value to the program. Syntax Val(argument)

39 Chapter 3 Part 139 Val Function intCount = Val(txtData.Text) Val function receives data from text property of the txtData text box control. converts argument from a string to a numeric value. returns the numeric value to the statement that called the function

40 Chapter 3 Part 140 Val Function intCount = Val(txtData.Text) Returns number 45 from the string 45 String “45”

41 Chapter 3 Part 141 Val Function Examples (p. 126) StringConversion “34.90”34.9 “86abc”86 “$24.95”0 “3,789”3 “x29”0

42 Chapter 3 Part 142 ToString (p. 126) Returns a string equivalent of data stored in a variable (sometimes used for output) Dim intNumber As Integer = 123 lblNumber.Text = intNumber.ToString

43 Chapter 3 Part 143 Option Strict On (pp. 126-127) Prevents VB from performing most implicit type conversions. Reduces errors that might result from implicit data type conversions. Must appear at the top of the code window before any other statements (after programmer ID remarks)

44 Chapter 3 Part 144 Section 3.4 Arithmetic Operators Calculations

45 Chapter 3 Part 145 Arithmetic Operators +Addition -Subtraction *Multiplication /Division ^Exponentiation

46 Chapter 3 Part 146 Arithmetic Examples decAmount = 4 + 8 (but has magic #s) dblTotal = dblPrice + dblTax decArea = decLength * decWidth dblAverage = dblTotal / intNumber dblResult = Val(txtInput.Text) * _ dblUNIT_PRICE

47 Chapter 3 Part 147 Warning When performing division, be sure that the operand to the right of the / operator is NOT zero. An error results if you divide by zero.

48 Chapter 3 Part 148 Special Division (p. 129) Integer Division\ Result is always an integer intParts = 17 \ 3 intParts contains value 5 MOD Operator Modulus operator returns remainder of division intLeftOver = 17 MOD 3 intLeftOver contains 2

49 Chapter 3 Part 149 Order of Precedence 1. Exponentiation 1 st 2. Multiplication and Division 3. Integer Division 4. Modulus 5. Addition and Subtraction

50 Chapter 3 Part 150 Examples Outcome = 12 + 6 / 3 Outcome = 12 + 2 Outcome = 14 Outcome = (12 + 6) / 3 Outcome = 18 / 3 Outcome = 6

51 Chapter 3 Part 151 More on Calculations Algebra Class 6y means multiply 6 by y Programming Class 6 * y is required Must use operator

52 Chapter 3 Part 152 Combined Assignment Operators Add current variable contents to 5 and save back to same variable intNumber = intNumber + 5 intNumber += 5 Multiply current variable contents by 10 and save back to same variable intOutcome = intOutcome * 10 intOutcome *= 10

53 Chapter 3 Part 153 Type Conversion Functions Read pp. 135-136 on your own.

54 Chapter 3 Part 154 Checkpoints for Individual Review page 127 page 137


Download ppt "Chapter 3 Part 11 Variables, Constants, and Calculations Chapter 3 Section 3.3 Chapter 3 Section 3.4."

Similar presentations


Ads by Google