Download presentation
Presentation is loading. Please wait.
Published byPenelope Simmons Modified over 6 years ago
1
Chapter 3 Data Types, Variables, and Expressions
2
Chapter 3 Data Types, Variables, and Expressions
3
Terminology Data Type – a category of data. A description of how the computer will treat bits found in memory. Variable – a named location in memory, treated as a particular data type, whose contents can be changed. Constant – a named location in memory, treated as a particular type, whose contents cannot be changed. Declaration – the act of creating a variable or constant and specifying its type. Literal – a hard-coded piece of data, part of the statement and not based on a variable or constant declaration. Operator – a symbol that describe how to manipulate data and variables in memory Expression – a combination of operators, variables, constants and/or literals that produces a resulting piece of data Assignment – copying the results of an expression into a variable. Statement – a program instruction telling the CPU what to do. Date Type: Just telling the program it is a number or a string Operator: + , - , / , *
4
Numbers Arithmetic Operations : Numeric Data Types: Integer, Double
+, -, /, *, \ (integer division), Mod (modulus, remainder), ^ (exponentiation) Numeric Data Types: Integer, Double Numeric Literals: (e.g. 10, 12.2, 0.395) Numeric Variables Declaration, Assignment, Use in expressions Numeric Expressions Some Built-In Arithmetic Functions: Math.Sqrt, Int, Math.Round
5
Arithmetic Operations
Arithmetic operations in Visual Basic + addition - subtraction * multiplication / division ^ exponentiation \ integer division (remainder is discarded) Mod modulus (remainder of an integer division) Modulus: What’s left over when you do the division. So 10 / 6 = 4. 6 goes into 10 one time. 4 is left over. So the left over or Modulus is 4.
6
Operator Precedence in Numeric Expressions
Exponentiation (^) Unary identity and negation (+, –) Multiplication and floating-point division (*, /) Integer division (\) Modulus arithmetic (Mod) Addition and subtraction (+, –) first last Same-precedence operations occur in left-to-right order Parenthesis give the operation priority. Parentheses can be used to override normal precedence (inner parentheses happen before outer parentheses)
7
Numeric Expressions 2 + 3 3 * (4 + 5) 2 ^ 3 13.2 + 4.5 / 3
All of these expressions involve numeric literals and arithmetic operators 14.7 Question: what will be the result of each of these expressions?
8
Two Integer-Valued Operators
Integer division (denoted by \) is similar to ordinary long division except that the remainder is discarded. The Mod operator returns only the integer remainder. 23 \ 7 = Mod 7 = 2 8 \ 2 = Mod 2 = 0
9
Numeric Variable A numeric variable is a named location in memory that will contain a number and can be modified throughout the program’s execution. Example variable names: intSpeed intDistance dblInterestRate dblBalance
10
Numeric Variable Declaration
Variable declaration (a statement beginning with Dim): Dim dblSpeed As Double variable name data type This creates a location in memory for containing a Double value. The Double data type refers to a number that can include a fractional part (i.e. places to the right of the decimal place.
11
Numeric Variable Declaration
You can declare multiple variables in the same Dim statement Dim dblA, dblB As Double This creates two Double variables Dim dblA As Double, intB As Integer This creates one Double variable and one Integer variable The Integer data type refers to a whole number (no fractional part included)
12
Numeric Variable Assignment
In an assignment statement, the expression to the right of the = operator is fully evaluated first, then the resulting value is placed in the variable to the left of the = operator. Assignment: intSpeed = 50 dblBal = dblBal + dblBal* dblInterestRate variable name Numeric expression What is dblBal after stmt is run if dblBal = 100 and dblInterestRate = 5% Note: the = symbol is an assignment operator in this case. Sometimes it is used as a test for equality (a relational operator), for example if used in a test of an If-statement
13
Initialization Numeric variables are automatically initialized to 0:
Dim varName As Double To specify a nonzero initial value Dim varName As Double = 50 Initialization is a variable declaration combined with an assignment
14
Example 3.1.2 This is a ListBox called lstResults
15
Variable declarations
Example 3.1.2 Variable declarations Variable intA is uninitialized so starts with a value of 0. Variable intB is initialized to 3.
16
Calling methods of the ListBox object’s Items property
Example 3.1.2 Calling methods of the ListBox object’s Items property The Clear method empties the Listbox. The Add method adds a row to the ListBox.
17
Anatomy of a Method Call
When calling the Add method, you pass it the data as an argument. The ListBox lstResults.Items.Add(intA) The Items property contains the collection of data that are displayed in the ListBox The Items property’s Add method is a subroutine that places an item into the collection
18
Example 3.1.2 Assigning value into the a variable
19
Example 3.1.2 Adding a third item to the list
20
Method Call passing a complex expression as an argument
lstResults.Items.Add(intA * (2 + intB)) An argument can be a complex expression. The expression will be fully evaluated before the resulting data is sent. In this case, the following steps take place in this order: 2 + intB innermost parentheses 5 Multiply intA times the results of (1) 25 Pass the result of (2) to the Add method Order of operations from innermost to outermost based on parentheses
21
Incrementing To add 1 to the numeric variable var Or as a shortcut
var = var + 1 Or as a shortcut var += 1 Or as a generalization var += numeric expression Other shortcuts: -=, *=, /=, etc.
22
Some Built-in Arithmetic Functions
Functions return a value Square root: Math.Sqrt(9) returns 3 Convert number to integer: Int(9.7) returns 9 Rounding: Math.Round(2.7) returns 3 NOTE: integer variables round the number but Int function truncates
23
Example 3.1.4 This is a ListBox called lstResults
24
Variable declarations
Example 3.1.4 Variable declarations
25
Example 3.1.4 Variable assignments
26
Empty the list box items
Example 3.1.4 Empty the list box items
27
Add three values to the list box
Example 3.1.4 Add three values to the list box
28
Order of operations lstResults.Items.Add(Math.Sqrt(5 * dblB + 1)) 15
16 4 Add to list
29
Order of operations lstResults.Items.Add(Int(dblA ^ dblB + 0.8)) 8 8.8
Add to list The Int function truncates the number…it will not round up, but rather just chops off the fractional part.
30
Order of operations lstResults.Items.Add(Math.Round(dblA / dblB, 3))
… 0.667 Add to list The Math.Round method rounds the number either up or down, depending on which rounded value is nearer. It can take two arguments: The number to be rounded The total number of decimal places for the rounded number If the second argument is not provided, 0 is assumed. There will be no decimal places, so the result will be a whole number. Multiple arguments to methods are separated by commas.
31
This example converts 41 inches into 3 feet, 5 inches
32
Variable declarations…three in one statement
Example 3.1.5 Variable declarations…three in one statement
33
Example 3.1.5 Backslash is for integer division. Truncates the fractional part. So, feet = 3
34
Example 3.1.5 Mod gives the remainder of an integer division. So, inches = 5. 41 divided by 12 is 3, with a remainder of 5
35
Widening Widening: assigning an Integer value to a Double variable
Widening always works. No conversion function needed.
36
Narrowing Narrowing: assigning a Double value to an Integer variable
Narrowing might not work. Narrowing requires the Cint function.
37
String Literal A string literal is a sequence of
characters surrounded by quotation marks. Examples: "hello" " " "#ab cde?"
38
String Variable Examples: A string variable is a name to which a
string value can be assigned. Examples: strCountry strSsn strWord strFirstName
39
String Variable (continued)
Declaration: Dim strFirstName As String variable name data type Assignment: strFirstName = "Fred" Remember – in general an assignment statement has a variable name to the left of = and an expression to the right. The data type of the expression should be consistent with the data type of the variable. For example, you should not assign a String expression into a Double variable.
40
Initial Value of a String Variable
By default the initial value is the keyword Nothing Strings can be given a different initial value as follows: Dim strName As String = "Fred“ The string "", which has no characters, is called the empty string or the zero-length string.
41
Example 3.2.1 This is a string literal, which will be displayed literally. This is a string variable, so its contents will be displayed
42
Concatenation Combining two strings to make a new string
strQuote1 = "We'll always " strQuote2 = "have Paris." strQuote3 = strQuote1 & strQuote2 & " - Humphrey Bogart" The variable called strQuote3 will contain: We'll always have Paris. - Humphrey Bogart Concatenation can be done using either the ampersand symbol (&) or the plus symbol (+)
43
Appending To append str to the string variable var Or as a shortcut
var = var & str Or as a shortcut var &= str
44
What are the results of each?
Appending Example Dim str1 As String = "Good" Dim str2 As String = "bye“ Dim str3 As String = "Good“ Dim str4 As String = "-bye" str1 + str2 str1 & str2 str1 &= str2 str3 += str4 What are the results of each?
45
Example 3.2.3
46
Declaring three String variables
Example 3.2.3 Declaring three String variables
47
Assigning String literals into String variables.
Example 3.2.3 Assigning String literals into String variables.
48
Example 3.2.3 Concatenating the contents of two String variables and assigning them into another String variable Note: remember that the right side of an assignment statement is an expression. In this example, the expressions are String expressions.
49
Example 3.2.3 The final result placed in the Text property of txtOutput is the result of another concatenation
50
Strings String Properties and Methods: Length ToUpper Trim ToLower
IndexOf Substring
51
String Properties and Methods
"Visual".Length is 6. "Visual".ToUpper is VISUAL. "123 Hike".Length is 8. "123 Hike".ToLower is 123 hike. "a" & " bcd ".Trim & "efg" is abcdefg. Properties are data items associated with a class of objects. Methods are functions or subroutines associated with a class of objects. These will be discussed in detail in future lectures.
52
Positions in a String Positions of characters in a string are numbered 0, 1, 2, …. Consider the string “Visual Basic”. Position 0: V Position 1: i Position 7: B Substring “al” begins at position 4
53
Substring Method Let str be a string.
str.Substring(m, n) is the substring of length n, beginning at position m in str. “Visual Basic”.Substring(2, 3) is “sua” “Visual Basic”.Substring(0, 1) is “V”
54
IndexOf Method Let str1 and str2 be strings.
str1.IndexOf(str2) is the position of the first occurrence of str2 in str1. (Note: Has value -1 if str2 is not a substring of str1.) "Visual Basic".IndexOf("is") is 1. "Visual Basic".IndexOf("si") is 9. "Visual Basic".IndexOf("ab") is -1.
55
Example 3.2.5 This example illustrates the use of some String methods and properties.
56
Example 3.2.5 The Substring method takes two arguments:
The beginning position of the substring (first position of the string is 0) The length of the substring (number of characters to return) Note: if no ending character position listed, returns to end of string
57
Example 3.2.5 This IndexOf method returns the first position of a substring within a string.
58
Example 3.2.5 This ToUpper method converts the characters of a string to upper case. There is also a ToLower method In this case, the string expression is a concatenation. Note that (str1 & str2) is a concatenation of two strings. Because this is in parentheses, the concatenation occurs BEFORE the conversion to upper case. What would happen if you did not have the parentheses around str1 & str2?
59
Example 3.2.5 The Trim method removes beginning and end spaces from a string. Here, the trim takes place for str1, and the result is concatenated with str2
60
Example 3.2.5 The Length property of a string gives the total number of characters in the string. As you can see, str2 contains “a wink”, which has a total of six characters In this case, the Substring method is only taking ONE argument (str2.Length – 4) 2. If a second argument is not provided Substring returns the remainder of the string, starting at the specified beginning position So, at the end of the assignment statement, str3 contains the string “wink”.
61
Example 3.2.5 Note: These methods (SubString, IndexOf, Trim, ToUpper) return a string expression that can be used for display or assignment. But they do NOT change the original contents of the variables str1 and str2. Only an assignment changes them. So, at the end of this program, the contents of str1 and str2 are still “Quick as ” and “a wink”.
62
Option Strict & Option Explicit
Visual Basic allows numeric variables to be assigned strings and vice versa, a poor programming practice. To prevent such assignments, set Option Strict & Option Explicit to On in the Options dialog box. Option Strict – requires explicit conversion of variable type Option Explicit – requires all variables to be declared
63
Option Strict & Explicit (continued)
Select Options from the Tools menu In left pane, expand Projects and Solution Select VB Defaults Set Option Strict to On Set Option Explicit to On
64
Option Strict (continued)
65
Auto Correction
66
With Option Strict On Not Valid: Replace with:
Dim dblVar As Double, intVar As Integer Dim strVar As String Not Valid: Replace with: intVar = dblVar intVar = CInt(dblVar) dblVar = strVar dblVar = CDbl(strVar) strVar = intVar strVar = CStr(intVar)
67
converts a String to a Double converts a number to a string
Data Conversion Because the contents of a text box is always a string, sometimes you must convert the input or output. dblVar = CDbl(txtBox.Text) txtBox.Text = CStr(numVar) converts a String to a Double converts a number to a string
68
Example 3.2.2 This example adds the values in two textboxes and places them in a third
69
Example 3.2.2 The CDbl function takes a string value and attempts to convert it into a Double value. Note: the string must consist of digits (and perhaps one dot for a decimal point). Otherwise an exception (run-time error) would occur.
70
Example 3.2.2 The CStr function takes a numeric value and converts it to a string. This is necessary because a TextBox’s Text property requires a string value.
71
Named Constants Declared with Value cannot be changed. Examples:
Const CONSTANT_NAME As DataType = value Value cannot be changed. Examples: Const MIN_VOTING_AGE As Integer = 18 Const INTEREST_RATE As Double = 0.035 Const TITLE As String = "Visual Basic"
72
Dates Date literal: #7/4/1776# Declarations: Dim datDay As Date
Dim datD As Date = CDate(txtBox.Text) Dim datDay As Date = #7/4/1776# Date literals are enclosed in pound signs #. The CDate function converts a string to a date.
73
Example 3.3.1 Working with dates
In this case, we have declared a variable as a Date.
74
Here we guarantee that only numbers are entered separated by slashes
Example 3.3.1 Note that we have set a mask in the mtbDayOfBirth MaskedTextBox control. The MaskedTextBox’s Mask property helps guide the user and prevent invalid input. Here we guarantee that only numbers are entered separated by slashes
75
Masked Text Box Control
Click on the Tasks button to reveal the Set Mask property. Click Set Mask to invoke the Input Mask dialog box.
76
Input Mask Dialog Box
77
Mask A Mask setting is a sequence of characters, with 0, L, and & having special meanings. 0 Placeholder for a digit. L Placeholder for a letter. & Placeholder for a character
78
Sample Masks State abbreviation: LL Phone number: 000-0000
Social Security Number: License plate: &&&&&& Date: 00/00/0000
79
The CDate function converts a String to a Date
Example 3.3.1 The CDate function converts a String to a Date
80
Example 3.3.1 The FormatDatetime takes a date and formats it four output. Options are LongDate, ShortDate, GeneralDate, Longtime, and ShortTime
81
Example 3.3.1 The DateDiff function gives the time gap between two dates. You can specify which intervals you want: days, months, etc.
82
Example 3.3.1 FormatNumber allows you to display a number in a wide variety of formats. In this case we are specifying to display only the whole number part of the difference. As always, use parentheses to determine the order of operations that take place…inner to outer.
83
Formatting Numbers Lots of approaches:
FormatNumber is good for getting the correct number of places to the right of the decimal, and has other options for how to display negative numbers, etc. FormatCurrency is a great way to show dollars and cents. For example, try this: FormatCurrency(varName) Where varName is the name of a numeric variable
84
Three Types of Errors Syntax error Runtime error Logic error
85
Some Types of Syntax Errors
Misspellings lstBox.Itms.Add(3) Omissions lstBox.Items.Add(2 + ) Incorrect punctuation Dim intM; intN As Integer
86
Syntax Error List Window
Dim intM; intN As Double lstResults.Items.Add(5 lstResults.Items.Add(a)
87
A Type of Runtime Error Overflow error – this is an Exception, and will cause the program to abort unless caught. Dim intVar As Integer = 10,000,000,000 intVar = intVar * intVar This is because a variable of Integer data type can only be assigned whole number values between about -2 billion and 2 billion. If you want larger numbers, you can use the Long data type.
88
A Logical Error Value of dblAverage will be 10. Should be 7.5.
Dim dblAverage As Double Dim intM As Double = 5 Dim intN As Double = 10 dblAverage = intM + intN / 2 Value of dblAverage will be 10. Should be 7.5. This is because division takes place before addition. Using parentheses to override normal operator precedence will make this correct: dblAverage = (intM + intN) / 2
89
Code comments Commented code begins with ‘ and is green
‘determine if user has more input Required in all remaining programs: 'Program name: 'Student name: 'My submission of this program indicates that I ‘have neither received nor given substantial ‘assistance in writing this program.
90
Example 3.2.7 It is good programming practice (and required in this class) to include comments in your code in order to explain what is being done.
91
Example 3.2.8 In previous examples, the variables were declared INSIDE the procedure. Here, it is declared OUTSIDE any subroutines. Two things to note about class-level variables: Their data remain in existence throughout the entire time that the Form is running Their data is accessible by ALL subroutines and functions of the form
92
Example 3.2.8 Compare previous to what would happen if numTimes were declared INSIDE the procedure. In this case, numTimes would only exist as long as the subroutine was running, and would disappear when it ended. So, EVERY TIME you run the routine, it will reinitialize to zero. Wouldn’t be able to keep a count of how many times the button was pushed!
93
3 Program Modes Design mode Run mode Debug or Break mode
94
Stepping through program
Execute one line of code at a time (Stepping into) Execute one procedure (Stepping over) Execute remaining lines of code (Stepping out) Execution will stop a pre-specified line of code (Break point) Hoover to see value of particular variable or object
95
Stepping through program
Each line is highlighted before execution Hover to see values dblNum1 & both Textboxes dblNum2 is 0 – Why?
96
Break points Set a break point & run Program stops Hover to see values
97
Book errors / Good programming techniques
Use 3 letter prefix for all objects and variables All controls and variables names must be descriptive Any control that should not be editable should be set as such if not by default Descriptive comments (do not repeat code) NOTE: book does not follow these but they are required in this class
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.