1 / 42

Chapter 3 Data Types, Variables, and Expressions

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.

tavita
Télécharger la présentation

Chapter 3 Data Types, Variables, and Expressions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 3Data Types, Variables, and Expressions

  2. 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.

  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)

  5. 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)

  6. 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?

  7. 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

  8. 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

  9. 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.

  10. 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)

  11. 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

  12. 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

  13. 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.

  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

  15. Widening • Widening: assigning an Integer value to a Double variable • Widening always works. (Every Integer value is a Double value.) • No conversion function needed.

  16. 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.

  17. String Literal A string literal is a sequence of characters surrounded by quotation marks. Examples: "hello" "123-45-6789" "#ab cde?"

  18. String Variable A string variable is a name to which a string value can be assigned. Examples: country ssn word firstName

  19. 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.

  20. 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.

  21. 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 (+)

  22. Appending • To append str to the string variable var var = var & str • Or as a shortcut var &= str

  23. Appending Example Dim var As String = "Good" var &= "bye" Resulting value in var:Goodbye

  24. Strings • String Properties and Methods:

  25. 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.

  26. 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

  27. 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”

  28. 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.

  29. 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.

  30. 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.

  31. Option Strict (continued) • Select Options from the Tools menu • In left pane, expand Projects and Solution • Select VB Defaults • Set Option Strict to On

  32. Option Strict (continued)

  33. Auto Correction

  34. 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)

  35. 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

  36. 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"

  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

  39. Syntax Error List Window Dim m; n As Double lstResults.Items.Add(5 lstResults.Items.Add(a)

  40. 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.

  41. 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

  42. 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.

More Related