Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Introduction to Numeric Data Types and Variables.

Similar presentations


Presentation on theme: "Chapter 4 Introduction to Numeric Data Types and Variables."— Presentation transcript:

1 Chapter 4 Introduction to Numeric Data Types and Variables

2 Class 4: Numeric Data Types Process numeric data Declare and use variables Create user-defined constants and use expressions Work with numeric data types and convert data between numeric and string data types Define the order in which control instances get input focus

3 Integral Data Types Integral data types store data that does not have a decimal point Some integral data types can store 0 or positive values Other integral data types can store both positive and negative values –Negative values are indicated by a sign bit –Unsigned data types were new to Visual Studio 2005

4 Table 4-1: Integral Data Types

5 Understanding Integral Data Types All integral values are stored as binary numbers The SByte data type stores its data in 8 bits –7 bits store the data –1 bit stores the value's sign The largest possible value is 2^7-1 or 127 The value has the binary pattern 01111111

6 Understanding Integral Data Types (continued) Negative integral values appear in two ’ s compliment format Rules to represent a two ’ s compliment value: –Start with the binary representation of a positive number –Flip each bit 0 values become 1 1 values become 0 –Add one to the number produced in the previous step

7 Creating a Negative Two ’ s Compliment Value Start with the positive representation of a value 0010 1010 Flip each bit 1101 0101 Add one to the value from the previous step 1101 0110

8 Introduction to Floating-point Data Types Floating-point numbers store values with a decimal point –Floating-point numbers are stored in a form of scientific notation One bit is the sign bit A 23-bit mantissa stores the fractional part of a number The exponent is stored in 8 bits

9 Table 4-3: Floating-point Data Types

10 Figure 4-4: Representation of a 32- bit Single Precision Value

11 Rounding Error (Introduction) Floating-point numbers are an approximation of an actual value –1/3 or 2/3 must be rounded, for example Rounding introduces an error called rounding error The greater the precision of the data type, the smaller the rounding error –The Decimal data type has the smallest rounding error and the greatest precision

12 Performance of Numeric Data Types Performance is a key characteristic of any application Different data types have different performance characteristics –Arithmetic operations using integral data types are faster than operations on floating-point data types –The Decimal data type is very slow

13 Introduction to the String Data Type Data is often represented as a string of characters –Textual data is represented as a string –Data entered by end users is textual –Strings are used to display output Strings are represented differently than numbers (numeric data types)

14 Storage of the String Data Type Strings are stored as Unicode characters in two bytes as an unsigned short ( UShort ) The first 127 values store letters, digits, and special characters The values 128 to 255 are for special characters such as keyboard arrows The values 256 to 65,535 are for international characters and diacritical marks

15 Figure 4-7: Representation of a Unicode string

16 Introduction to Value Types and Reference Types A data type can be characterized as a value type or a reference type –Value types store data in the memory allocated to the variable –Reference types store a 32-bit memory address

17 Value Types All value types derive from the System.ValueType class Integral and floating-point data types are value types

18 Figure 4-8: Storage of value types

19 Reference Types All reference type variables are 32 bits in size The value stored in a reference type variable is a memory address This memory address points to the memory allocated to the actual data –Thus, the term pointer is often used to describe a reference type

20 Figure 4-9: Storage of reference types

21 Introduction to Variables A variable stores data while an application runs –The process of creating a variable is called declaring a variable –A variable has a name (identifier) The naming rules for variables and procedures are the same –A variable has a data type

22 Variable Characteristics All variables have three characteristics –A variable has a lifetime –A variable has a scope –A variable has accessibility

23 Variable Lifetime Variable lifetime refers to the period of time that a variable exists –A variable with local lifetime exists only while a procedure executes –A variable with a module-level lifetime exists while a class instance exists or a module is loaded

24 Variable Scope and Accessibility Variable scope refers to the statements that can use a variable Variables declared inside a procedure with the Dim statement have local scope Variables declared outside a procedure with the Private statement have module-level scope

25 Declaring a Local Variable [Dim | Static] varname As type [=initexpr] –The Dim keyword declares a local variable The variable and its value are destroyed when the procedure ends –The Static keyword declares a local variable The variable and its value persist from one procedure invocation to the next –varname contains the name (identifier) of the variable –type defines the variable ’ s data type –initexpr is used to initialize the variable ’ s value

26 Initializing Variables Variables can be declared and initialized in the same statement Example to declare a variable named CurrentYear and initialize its value to 2006: Dim CurrentYear As Integer = 2006

27 Common Initialization Errors Numeric initialization values cannot contain formatting characters The following statements are illegal: Dim Value1 As Double = 100,000.52 Dim Value2 As Double = $100,000.52

28 Declaring Multiple Variables in One Statement Multiple variables can be declared in the same statement Separate each declaration with a comma as follows: Dim IntegerValue As Integer, _ DoubleValue As Double If variables have the same data type, the following shorthand notation can be used: Dim IntegerValue1, IntegerValue2 As Integer

29 Naming Conventions (Description) Hungarian notation –Use a prefix to denote the data type followed by a descriptive name Pascal case –Use whole words –Capitalize the first letter of each word Camel case –Use whole words –Use lower case for the first letter of the first word –Capitalize the first letter of each remaining word

30 User-defined Constants Constants are similar to variables The value of a constant does not change while an application runs –Trying to assign a value to a constant will cause an error Use the Const statement to declare a constant Constants are typically declared at the module-level

31 User-defined Constant (Example) Declare a constant to store the value of PI Private Const PI_VALUE As Single _ = 3.14159 Declare a constant to store the value of PI multiplied by 2 Private Const PI_VALUE As Single _ = PI_VALUE * 2

32 Introduction to Expressions Variables can be used in assignment statements along with object properties Examples: Dim Result As Integer Dim Example As Integer = 4 Result = 3 Result = txtExample.Height Result = Example

33 Common Expression Errors Values on the right and left sides of an assignment statement must have the same data type The Font and Integer data types are not compatible so the following statements will cause an error: Dim SomeInteger As Integer SomeInteger = txtExample.Font

34 Parts of an Expression Operators –Arithmetic operators such as (+, -, *, /, ^, \) –Comparison and logical operators Operands –Literal values –Object properties –Constants –Variables

35 Operator Precedence Operators have an evaluation order called precedence –The Visual Basic precedence rules are the same as the algebraic precedence rules –Use parentheses to override the default precedence rules –Use parentheses to clarify evaluation order Extra parentheses do no harm

36 Table 4-5: Operators and Precedence

37 Arithmetic Operators (Example) Divide 10 by 5 and multiply the intermediate result by 100 The value 200 is stored in Result Dim Numerator As Double = 10 Dim Denominator As Double = 5 Dim Result As Double Result = Numerator / Denominator * 100

38 Integer Division The result of an integer division operation is an integral value The result is truncated rather than rounded Examples: Result = 4 \ 3 ' 1 Result = 5 \ 2 ' 2 Result = 10 \ 6 ' 1

39 The Mod Operator The Mod operator calculates the Integer remainder of a division operation –The operation is the same as the remainder resulting from a long division operation Examples: Result = 5 Mod 2 ' 1 Result = 4 Mod 2 ' 0

40 Operator Precedence Arithmetic operators are applied in a default order known as precedence –Exponentiation, multiplication and division, addition and subtraction Use parentheses to change the default precedence order

41 Figure 4-11: Evaluation Order with and without Parenthesis

42 Numeric Data Types and Type Conversion Type conversion is used to convert data from one data type to another How type conversion is performed depends on whether strict type checking is enabled or disabled –If strict type checking is enabled, less restrictive types will not be implicitly converted to more restrictive types –Strings will not be implicitly converted to numeric data types

43 Strict Type Checking Rules Widening type coercion allows more restrictive types to be implicitly converted to less restrictive types –Integral data types will be converted to floating-point types –Integer to Single is legal, for example –Single to Double is legal –Double to Integer is not legal

44 Enabling Strict Type Checking The Option Strict statement enables or disables strict type checking The Option Strict statement must appear at the beginning of a module Enable strict type checking to prevent hard to find type conversion errors Example: Option Strict On Option Strict Off

45 Enforcing Explicit Variable Declaration Explicit variable declaration requires variables to be declared before they are used –Explicit variable declaration is enabled, by default Use the Option Explicit statement to enforce explicit variable declaration Example: Option Explicit On Option Explicit Off

46 Performing Explicit Type Conversion The members of the System.Convert class explicitly convert data from one type to another Methods exist for each primary data type Example: Dim DoubleValue1 As Double = 123.44 Dim IntegerResult As Integer IntegerResult = _ System.Convert.ToInt32(DoubleValue1)

47 Explicit Type Conversion Methods ToInt16, ToInt32, and ToInt64 convert the argument to an integral value ToDecimal converts the argument to the Decimal data type ToDouble and ToSingle convert the argument to floating-point data types ToString converts the argument to a string

48 Formatting Output Strings The ToString method accepts an argument used to format numeric data –Visual Studio supports named formats to supply common formatting Currency, for example –Predefined formats can be created with format specifiers –Custom formats can be created with placeholder characters

49 Table 4-6: Format Specifiers

50 Table 4-7: Placeholder Characters

51 Table 4-8: Format Strings

52 The Imports Statement Use the Imports statement to eliminate the need for fully qualified references to method names The Imports statement appears after the Option Explicit and Option Strict statements It ’ s possible to import any number of namespaces or classes The order in which Imports statements appear is not significant Types can also be imported using the Project Properties dialog box

53 Imports Statement (Example) Import the System.Convert class Option Explicit On Option Strict On Imports System.Convert Public Class frmMain ' statements End Class

54 Figure 4-14: Project Properties Dialog Box

55 The FV Function The FV function calculates the future value of an investment The first argument contains the interest rate The second argument contains the number of periods The third argument contains the amount of the periodic payment The optional fourth argument contains the present (initial) value of the investment The optional fifth argument defines whether payments are made at the beginning or end of the period

56 The FV Function (Example) Calculate the future value of $1,000.00 for 12 periods at 1% per period Dim MonthRate As Integer = 0.01 Dim MonthTerm As Integer = 12 Dim InitialValue As Single = 1000.00 Dim FutureValue As Double FutureValue = FV(0.01, 12, 0, 1000) FutureValue = FV (MonthRate, MonthTerm, 0, _ InitialValue)

57 The TextBox Control (Introduction) The TextBox control gets input and displays output –The control derives from the TextBoxBase class –Other textual controsl include the MaskedTextBox and RichTextBox controls

58 The TextBox Control (Properties) The BorderStyle property defines the style of the border The ForeColor and BackColor properties define text and background colors The Enabled property defines whether the control instance can get input focus The ReadOnly property controls whether the text in the control instance can be copied to the clipboard The MultiLine property defines whether text will appear on multiple lines The maximum number of characters is defined in the MaxLength property

59 The TextBox Control (Properties, continued) The ScrollBars property defines whether scroll bars appear –Scroll bars only appear when the MultiLine property is True The Text property stores the visible text The TextAlign property defines how the text is aligned in the control instance The size and position is defined by the X, Y, Height, and Width properties

60 The TextBox Control (Methods and Events) The Focus method is used to set input focus to a text box The Enter event fires when the control instance gets focus The Leave event fires when the control instance loses focus

61 Introduction to Tab Order Every form has exactly one active control instance at run time –This is the control instance having input focus The order in which control instances get focus is called the tab order –The tab order is set using the TabIndex property –The tab order can also be set using a visual designer

62 Figure 4-14: Setting the tab order


Download ppt "Chapter 4 Introduction to Numeric Data Types and Variables."

Similar presentations


Ads by Google