CHAPTER 3 DATA TYPES VARIABLES AND EXPRESSIONS 1
CHAPTER 3 DATA 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
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 3
Arithmetic Operations • Arithmetic operations in Visual Basic integer division + addition (remainder is - subtraction discarded) * multiplication / division Mod modulus ^ exponentiation (remainder of an integer division) 4
Operator Precedence in Numeric Expressions first • Exponentiation (^) • Unary identity and negation (+, –) Same-precedence • Multiplication and floating-point operations occur division (*, /) in left-to-right order • Integer division () • Modulus arithmetic (Mod) • Addition and subtraction (+, –) last Parentheses can be used to override normal precedence (inner parentheses happen before outer parentheses) 5
Numeric Expressions 2+3 3 * (4 + 5) All of these expressions involve numeric literals and arithmetic operators 2^3 13. 2 + 4. 5 / 3 Question: what will be the result of each of these expressions? Text 49125 all 4 – separate w/comma, to 22333 6
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 82=4 8 Mod 2 = 0 7
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: speed distance interest. Rate balance 8
Numeric Variable Declaration • Variable declaration (a statement beginning with Dim): Dim speed 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. 9
Numeric Variable Declaration • You can declare multiple variables in the same Dim statement Dim a, b As Double This creates two Double variables Dim a As Double, b As Integer This creates one Double variable and one Integer variable The Integer data type refers to a whole number (no fractional part included) 10
Numeric Variable Assignment • Assignment: • speed = 50 variable name 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. Numeric expression • balance = balance + balance * interest. Rate What is balance after stmt is run if balance = 100 and interest. Rate = 5% Text 2813 to 22333 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 11
Initialization • Numeric variables are automatically initialized to 0: Dim var. Name As Double • To specify a nonzero initial value Dim var. Name As Double = 50 Initialization is a variable declaration combined with an assignment 12
Incrementing • To add 1 to the numeric variable var = var + 1 • Or as a shortcut var += 1 • Or as a generalization var += numeric expression Other shortcuts: -=, *=, /=, etc. 13
Some Built-in Arithmetic 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 14
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
String Literal A string literal is a sequence of characters surrounded by quotation marks. Examples: "hello" "123 -45 -6789" "#ab cde? " 17
String Variable A string variable is a name to which a string value can be assigned. Examples: country ssn word first. Name 18
String Variable (continued) • Declaration: Dim first. Name As String variable name data type • Assignment: first. Name = "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. 19
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 quote 1 = "We'll always " quote 2 = "have Paris. " quote 3 = quote 1 & quote 2 & " - Humphrey Bogart" The variable called quote 3 will contain: We'll always have Paris. - Humphrey Bogart Concatenation can be done using either the ampersand symbol (&) or the plus symbol (+) 21
Appending • To append str to the string variable var = var & str • Or as a shortcut var &= str 22
Appending Example Dim var As String = "Good" var &= "bye" Resulting value in var: Goodbye 23
Strings • String Properties and Methods: Length Trim Index. Of To. Upper To. Lower Substring 24
String Properties and Methods "Visual". Length is 6. "Visual". To. Upper is VISUAL. "123 Hike". Length is 8. "123 Hike". To. Lower 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. 25
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 26
Substring Method Let str be a string. is the substring of length n, beginning at position m in str. Substring(m, n) “Visual Basic”. Substring(2, 3) is “sua” “Visual Basic”. Substring(0, 1) is “V” 27
Index. Of Method Let str 1 and str 2 be strings. str 1. Index. Of(str 2) is the position of the first occurrence of str 2 in str 1. (Note: Has value -1 if str 2 is not a substring of str 1. ) "Visual Basic". Index. Of("is") is 1. "Visual Basic". Index. Of("si") is 9. "Visual Basic". Index. Of("ab") is -1. 28
Dates • Date literal: #7/4/1776# • Declarations: Date literals are enclosed in pound signs #. Dim ind. Day As Date Dim d As Date = CDate(txt. Box. Text) Dim ind. Day As Date = #7/4/1776# The CDate function converts a string to a date. 29
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
Auto Correction 33
With Option Strict On Dim dbl. Var As Double, int. Var As Integer Dim str. Var As String Not Valid: Replace with: int. Var = dbl. Var = str. Var = int. Var = CInt(dbl. Var) dbl. Var = CDbl(str. Var) str. Var = CStr(int. Var) 34
Data Conversion Because the contents of a text box is always a string, sometimes you must convert the input or output. dbl. Var = CDbl(txt. Box. Text) converts a String to a Double txt. Box. Text = CStr(num. Var) converts a number to a string 35
Named Constants • Declared with Const CONSTANT_NAME As Data. Type = 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
Three Types of Errors • Syntax error • Runtime error • Logic error 37
Some Types of Syntax Errors • Misspellings lst. Box. Itms. Add(3) • Omissions lst. Box. Items. Add(2 + ) • Incorrect punctuation Dim m; n As Integer 38
Syntax Error List Window Dim m; n As Double lst. Results. Items. Add(5 lst. Results. Items. Add(a) 39
A Type of Runtime Error Overflow error – this is an Exception, and will cause the program to abort unless caught. Dim num. Var As Integer = 1000000 num. Var = num. Var * num. Var 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. 40
A Logical Error Dim average As Double Dim m As Double = 5 Dim n As Double = 10 average = 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 41
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
- Slides: 42