Presentation is loading. Please wait.

Presentation is loading. Please wait.

Variables, Constants, and Calculations

Similar presentations


Presentation on theme: "Variables, Constants, and Calculations"— Presentation transcript:

1 Variables, Constants, and Calculations
Chapter 3 Variables, Constants, and Calculations McGraw-Hill Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.

2 Variables If you were told: X = 5 and Y = 10 and answer = x + y What would answer equal? Answer = 15

3 Variables Constant – this number cannot change while the pgm runs If you were told: r=10 and areaCircle = 3.14 * r ^2 What would areaCircle equal? Variable – the value can vary. Answer = 314

4 Circle Area in VB code Const PI as Double = R ‘declare constants before variables ‘the R means the number is a double Dim dblR as Double Dim dblCircleArea as Double dblR = 10 dlbCircleArea = PI * dblR ^ 2

5 Declaring Variables Declared inside a procedure using a Dim statement
Declared outside a procedure using Private Always declare the variable’s data type. Inside a procedure you must use the Dim statement. Declaration Statements—General Form: Public|Private|Dim Identifier [As Datatype]

6 Declaration Statement Examples
Dim strCustomerName As String Private intTotalSold As Integer Dim sglTemperature As Single Dim decPrice As Decimal Private decPrice VB’s IntelliSense feature helps you enter Private, Public, and Dim statements—after you type the space that follows VariableName As, a list pops up and displays the possible entries for data type to complete the statement. If you begin to complete the statement the list automatically scrolls to the correct section; when the correct entry is highlighted press Enter, Tab, or the spacebar to select the entry, or double-click if using the mouse. The reserve word Dim is really short for dimension, which means size. When declaring a variable, the amount of memory reserved depends on its data type.

7 Data Types Common ones will be circled Data Type Use For
Storage Size in bytes Boolean True or False value 2 Byte 0 to 255, binary data 1 Clear Single Unicode character Date 1/1/0001 through 12/31/9999 8 Decimal Decimal fractions, such as dollars/cents 16 Single Single precision floating-point numbers with six digits of accuracy 4 Double Double precision floating-point numbers with 14 digits of accuracy Short Small integer in the range -32,768 to 32,767 Integer Whole numbers in the range -2,147,483,648 to +2,147,483,647 Long Larger whole numbers String Alphanumeric data: letters, digits, and other characters Varies Object Any type of data The data type of a variable or constant indicates what type of information will be stored in the allocated memory space. The data type charts displays the kind of data each type of data types hold, and the amount of memory allocated. The most common types of variables and constants are String, Integer, and Decimal.

8 Naming Variables and Constants
Use camelCase & prefixes for variables (intQuantity) and UPPERCASE for constants (GST, PI) Cannot use reserved words or keywords to which Basic has assigned a meaning, such as print, name, and value Meaningful names consisting of letters, digits, and underscores; must begin with a letter and no spaces or periods. Include class (data type) of variable (variable: countInteger constant: QUOTA_Integer) A programmer has to name (identify) the variables and named constants that will be used in a project.

9 Type casting Dim intHeight as integer intHeight = 6.7 intHeight will now equal 7. It cannot hold a decimal value since it was declared type integer It will automatically be cast (rounded) to a whole number

10 Constants Named User assigned name, data type, and value
Use CONST keyword to declare. Intrinsic System defined within Visual Studio (Color.Red) Const COMPANY_ADDRESS As String = "101 S. Main Street" Const SALES_TAX_RATE As Doublel = .08R Constants provide a way to use words to describe a value that doesn’t change. Constants are declared using the keyword and are given a name, a data type, and a value. Once a value is declared as a constant, its value can’t be changed during the execution of the project. Data type declared and data type of the value must match. Many sets of intrinsic constants (key term) are declared in system class libraries and are available for use in VB programs.

11 Assigning Values to Constants
Declare the data type of numeric constants by appending a type- declaration character. Decimal D Decimal – D Double R Double – R Integer I Integer – I Long L Long – L Short S Single F Single – F If a type-declaration character is not appended, any whole number is assumed to be Integer and any fractional value is assumed to be Double. Use two quotes with a string literal to avoid confusion.

12 Scope and Lifetime of Variables (1 of 2)
Visibility of a variable is its scope. Scope may be Namespace Module level Local Block level Lifetime of a variable is the period of time the variable exists. A variable may exist and be visible for an entire project, for only one form, or for only one procedure. Visibility really means “this variable can be used or ‘seen’ in this location.” Namespace — Available to all procedures of project Module — Available to all procedures within that module (often a form) Use Public or Private keywords Local — Available only to the procedure in which it is declared Block — Available only in block of code inside a procedure where declared Previous versions of VB and some other programming languages refer to namespace variables as global variables.

13 Module Level Variable Declaration Example
Code module-level declarations in the Declaration section at the top of the code. To enter module-level declarations, you must be in the Editor window at the top of your code. Place the Private and Const statements after the Class declaration but before your first procedure.

14 Calculations Calculations can be performed with variables, constants, properties of certain objects, and numeric literals. Do not use strings in calculations. Values from Text property of Text Boxes Are strings, even if they contain numeric data Must be converted to a numeric data type before performing a calculation

15 Getting Input from a text box
intHeight = txtHeight.Text The above line works fine assuming that the user will not input anything except an integer. If they do, the program will crash.

16 Text changed procedures
If a calculation is performed and results outputted due to a textbox value, then if the value in that textbox is changed, the result label should be cleared, along with anything else on the interface that corresponds to the now non-existing textbox text property. Me.lblResult.Text=““

17 Got Focus When a text box receives the focus, the text inside the box should become selected, awaiting the user’s new input. txtNumber.SelStart =0 txtNumber.SelLength=Len(txtNumber)

18 Mod and div There is a video in Moodle explaining these two types of INTEGER division. When you divide 2 integers (not real numbers), you get a remainder (mod) and a dividend (div  \). Examples: 11 / 4 = 2 remainder 3 therefore: 11 mod 4 = 3 11 \ 4 = 2

19 debugging Now that you are performing calculations, you will need to learn how to debug your programs when the results are not what you expected them to be. There will be a video on moodle for an explanation on how to add breakpoints and step through your code.

20 Debugging with breakpoints
There will be times when you program is not producing the desired output. These logic errors can be tracked down using breakpoints. Add the breakpoints by clicking at the left of the line of code where you want to start debugging, and a red dot will appear. When the program halts on this line, right click on the variable in question to add a watch Click step into and continue stepping through your program, watching the values as your program runs. Clicking the dot will remove the breakpoint

21 Unexpected input from user
If you ask the user for a number, and they input something that isn’t a number, your program will crash (halt execution). Use the val function to convert non-numeric characters to a zero to keep the program from crashing. IintHeight=val(Me.txtHeight.Text) The val function will convert the retrieved string to a 0 if it begins with anything except an integer

22 Arithmetic Operations
Operator Operation + Addition – Subtraction * Multiplication / Division \ Integer Division Mod Modulus – Remainder of division ^ Exponentiation The arithmetic operations you can perform in VB include addition, subtraction, multiplication, division, integer division, modulus, and exponentiation. The first four operations are self explanatory, but you may not be familiar with Integer Division, Modulus, and/or exponentiation. Integer division — use to divide one integer by another giving an integer result, truncating (dropping) any remainder Modulus — returns the remainder of a division problem Exponentiation — raises a number to the power specified and returns (produces) a result of the Double data type.

23 Order of Operations (BEDMAS)
Hierarchy of operations, or order of precedence, in arithmetic expressions from highest to lowest 1. Any operation inside parentheses 2. Exponentiation 3. Multiplication and division 4. Integer division 5. Modulus 6. Addition and subtraction To change the order of evaluation, use parentheses.

24 Using Calculations in Code
Perform calculations in assignment statements. What appears on right side of assignment operator is assigned to item on left side. Assignment operators — allows shorter versions of code =, +=, -=, *=, /=, \=, &= ‘Accumulate a total. TotalSalesDecimal += salesDecimal The assignment operators that you will use most often are += and – =.

25 Rounding Numbers Round decimal fractions
Decimal.Round method returns a decimal result rounded to a specified number of decimal positions. Decimal.Round and Convert methods use technique called “rounding toward even.” Decimal Value to Round Number of Decimal Positions Results 1.455 2 1.46 1.445 1.44 1.5 2.5 See the Appendices for additional mathematical, financial, and string functions Example: ' Round to two decimal positions. ResultDecimal = Decimal.Round(AmountDecimal, 2)

26 Formatting Data for Display
To display numeric data in a label or text box, first convert value to string. Use ToString method Format the data using formatting codes. Specifies use of dollar sign, percent sign, and commas Specifies number of digits that appear to right of decimal point DisplayTextBox.Text = NumberInteger.ToString() When wanting to display numeric data in the Text property of a label or text box, the value must first be converted to string—the data can be formatted, which controls the way the output will look.

27 Using Format Specifier Codes
"C" code Currency — String formatted with dollar sign, commas separating each group of 3 digits and 2 digits to the right of decimal point "N" code Number — String formatted with commas separating each group of 3 digits and 2 digits to the right of decimal point Can specify number of decimal positions Example: "C0" zero digits The format specifier codes format the display of output and are predefined. The default format of each of the formatting codes is based on the computer’s regional setting. Format specifier codes are displayed on the next slide (Slide 30) and examples are shown on the following slide (Slide 31).

28 Format Specifier Codes
Name C or c Currency F or f Fixed-point N or n Number D or d Digits P or p Percent

29 Format Specifier Code Examples
Variable Value Code Output totalDecimal "C" $1,125.67 "N0" 1,126 pinInteger 123 "D6" 000123 rateDecimal 0.075 "P" 7.50% "P3" 7.500% "P0" 8% valueInteger -10 ($10.00)

30 Date Specifier Code Format DateTime values using format codes and ToString method. You can use methods of the DateTime structure for formatting dates:ToLongDateString, ToShortDateString, ToLongTimeString, ToShortTimeString. See Appendix B or MSDN for additional information.

31 Counting and Accumulating Sums
Declare module-level variables, since local level variables reset to 0 each time the procedure is called. Summing Numbers Counting Calculating an Average dblTotal += dblItemPrice Private intCounter As Integer intCounter += 1 Programs often need to calculate the sum of numbers. The technique for summing is to declare a module-level variable for the total. If you want to count something, you need another module-level variable. To calculate an average, divide the sum of the items by the count of the items. dblAverage = dblTotal / intCounter

32 App deployment When your wonderful program is ready for the world, you can deploy it by publishing it to an URL, FTP location, or a space on your file server. There is a wizard to guide you

33 Assignments and practice
Case Study, LVP Book Hands on Programming Example, Ch 3, Bradley Pizza Cost, LVP Change, LVP DigitsofaNumber International Lennies Bail Bonds, 3.2 Bradley Recording Studio, 3.4 Bradley Car Rental, 3.7 Bradley Video Bonanza 3


Download ppt "Variables, Constants, and Calculations"

Similar presentations


Ads by Google