520 likes | 813 Views
Chapter 3 Data Types, Variables, and Expressions. 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.
E N D
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.
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
Arithmetic Operations • Arithmetic operations in Visual Basic + addition - subtraction * multiplication / division ^ exponentiation \ integer division (remainder is discarded) Mod modulus (remainder of an integer division)
first last Operator Precedence in Numeric Expressions • Exponentiation (^) • Unary identity and negation (+, –) • Multiplication and floating-point division (*, /) • Integer division (\) • Modulus arithmetic (Mod) • Addition and subtraction (+, –) Same-precedence operations occur in left-to-right order Parentheses can be used to override normal precedence (inner parentheses happen before outer parentheses)
Numeric Expressions 2 + 3 3 * (4 + 5) 2 ^ 3 13.2 + 4.5 / 3 Text 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
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 interestRate balance
Numeric Variable Declaration • Variable declaration (a statement beginning with Dim): Dim speed As Double data type variable name 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 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)
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: • speed = 50 • balance = balance + balance * interestRate variable name Numeric expression • What is balance after stmt is run if balance = 100 and interestRate = 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
Initialization • Numeric variables are automatically initialized to 0: DimvarName AsDouble • To specify a nonzero initial value DimvarName AsDouble = 50 Initialization is a variable declaration combined with an assignment
Incrementing • To add 1 to the numeric variable var var = var + 1 • Or as a shortcut var += 1 • Or as a generalization var += numeric expression Other shortcuts: -=, *=, /=, etc.
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.
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.
String Literal A string literal is a sequence of characters surrounded by quotation marks. Examples: "hello" "123-45-6789" "#ab cde?"
String Variable A string variable is a name to which a string value can be assigned. Examples: country ssn word firstName
String Variable (continued) • Declaration: Dim firstName As String 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.
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 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 shortcut var &= str
Appending Example Dim var As String = "Good" var &= "bye" Resulting value in var:Goodbye
Strings • String Properties and Methods:
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.
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
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”
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.
Dates • Date literal: #7/4/1776# • Declarations: Dim indDay AsDate Dim d AsDate= CDate(txtBox.Text) Dim indDay AsDate = #7/4/1776# Date literals are enclosed in pound signs #. The CDate function converts a string to a date.
Option Strict • Visual Basic allows numeric variables to be assigned strings and vice versa, a poor programming practice. • To prevent such assignments, setOption Strict to On in the Options dialog box.
Option Strict (continued) • Select Options from the Tools menu • In left pane, expand Projects and Solution • Select VB Defaults • Set Option Strict to On
With Option Strict On 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)
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
Named Constants • Declared with ConstCONSTANT_NAMEAsDataType= value • Value cannot be changed. Examples: Const MIN_VOTING_AGE AsInteger= 18 Const INTEREST_RATE AsDouble= 0.035 Const TITLE AsString= "Visual Basic"
Three Types of Errors • Syntax error • Runtime error • Logic error
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)
A Type of Runtime Error Overflow error – this is an Exception, and will cause the program to abort unless caught. Dim numVar As Integer = 1000000 numVar = numVar * numVar 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.
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
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.