CHAPTER 3DATA TYPES, VARIABLES, AND EXPRESSIONS
1
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.
2
3
Numbers• Arithmetic Operations :
• +, -, /, *, \ (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
4
Arithmetic Operations• Arithmetic operations in Visual Basic
+ addition- subtraction* multiplication/ division^ exponentiation
\ integer division (remainder is discarded)
Mod modulus (remainder of an integer division)
Operator Precedence in Numeric Expressions
• Exponentiation (^)• Unary identity and negation (+, –)• Multiplication and floating-point
division (*, /)• Integer division (\)• Modulus arithmetic (Mod)• Addition and subtraction (+, –)
first
lastParentheses can be used to override normal precedence(inner parentheses happen before outer parentheses)
Same-precedence operations occur in left-to-right order
5
6
Numeric Expressions2 + 3
3 * (4 + 5)
2 ^ 3
13.2 + 4.5 / 3Text 49125 all 4 – separate w/comma, to 22333
All of these expressions involve numeric literals and arithmetic operators
Question: what will be the result of each of these expressions?
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 = 3 23 Mod 7 = 2 8 \ 2 = 4 8 Mod 2 = 0
7
8
Numeric VariableA 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:speed
distanceinterestRate
balance
Numeric Variable Declaration• Variable declaration (a statement beginning
with Dim):Dim speed As Double
9
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.
Numeric Variable Declaration• You can declare multiple variables in the
same Dim statement
10
The Integer data type refers to a whole number (no fractional part included)
Dim a, b As Double This creates two Double variables
Dim a As Double, b As IntegerThis creates one Double variable and one Integer variable
Numeric Variable Assignment• Assignment:
• speed = 50
• balance = balance + balance * interestRate
11
variable name Numeric expression
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
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.
What is balance after stmt is run if balance = 100 and interestRate = 5% Text 2813 to 22333
Initialization• Numeric variables are automatically
initialized to 0:Dim varName As Double
• To specify a nonzero initial valueDim varName As Double = 50
12
Initialization is a variable declaration combined with an assignment
13
Incrementing• To add 1 to the numeric variable var
var = var + 1
• Or as a shortcutvar += 1
• Or as a generalizationvar += numeric expression
Other shortcuts: -=, *=, /=, etc.
14
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
Widening• Widening: assigning an Integer value to
a Double variable• Widening always works. (Every Integer
value is a Double value.)• No conversion function needed.
15
Narrowing• Narrowing: assigning a Double value to an
Integer variable• Narrowing might not work. (Not every
Double value is an Integer value.)• Narrowing requires the Cint function.
16
17
String LiteralA string literal is a sequence ofcharacters surrounded by quotation marks.
Examples:"hello"
"123-45-6789""#ab cde?"
18
String VariableA string variable is a name to which astring value can be assigned.
Examples:countryssnword
firstName
String Variable (continued)• Declaration:
Dim firstName As String
19
variable name data type
• Assignment:firstName = "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.
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 name As String = "Fred“
The string "", which has no characters, is called the empty string or the zero-length string.
20
Concatenation Combining two strings to make a new string
quote1 = "We'll always "quote2 = "have Paris."quote3 = quote1 & quote2 & " - Humphrey Bogart"
The variable called quote3 will contain:We'll always have Paris. - Humphrey Bogart
21
Concatenation can be done using either the ampersand symbol (&) or the plus symbol (+)
Appending• To append str to the string variable var
var = var & str
• Or as a shortcutvar &= str
22
Appending ExampleDim var As String = "Good"var &= "bye"
Resulting value in var: Goodbye
23
24
Strings• String Properties and Methods:
Length ToUpperTrim ToLowerIndexOf Substring
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.
25
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.
Positions in a String Positions of characters in a string are
numbered 0, 1, 2, ….Consider the string “Visual Basic”.Position 0: VPosition 1: iPosition 7: BSubstring “al” begins at position 4
26
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”
27
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.
28
Dates• Date literal: #7/4/1776#
• Declarations: Dim indDay As Date Dim d As Date = CDate(txtBox.Text) Dim indDay As Date = #7/4/1776#
29
The CDate function converts a string to a date.
Date literals are enclosed in pound signs #.
Option Strict • Visual Basic allows numeric variables to be
assigned strings and vice versa, a poor programming practice.
• To prevent such assignments, set Option Strict to On in the Options dialog box.
30
Option Strict (continued)• Select Options from the Tools menu• In left pane, expand Projects and Solution• Select VB Defaults• Set Option Strict to On
31
Option Strict (continued)
32
33
Auto Correction
With Option Strict OnDim dblVar As Double, intVar As IntegerDim strVar As String
Not Valid: Replace with:intVar = dblVar intVar = CInt(dblVar)dblVar = strVar dblVar = CDbl(strVar)strVar = intVar strVar = CStr(intVar)
34
Data ConversionBecause 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)
35
converts a String to a Double
converts a number to a string
Named Constants• Declared with 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"
36
37
Three Types of Errors• Syntax error• Runtime error• Logic error
38
Some Types of Syntax Errors• Misspellings lstBox.Itms.Add(3)• Omissions lstBox.Items.Add(2 + )• Incorrect punctuation Dim m; n As Integer
Syntax Error List Window Dim m; n As Double lstResults.Items.Add(5 lstResults.Items.Add(a)
39
A Type of Runtime ErrorOverflow error – this is an Exception, and will
cause the program to abort unless caught.
Dim numVar As Integer = 1000000numVar = numVar * numVar
40
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.
41
A Logical ErrorDim average As DoubleDim m As Double = 5Dim n As Double = 10average = m + n / 2
Value of average 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:
average = (m + n) / 2
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.
42