chapter 3 data types, variables, and expressions

42
CHAPTER 3 DATA TYPES, VARIABLES, AND EXPRESSIONS 1

Upload: tavita

Post on 09-Feb-2016

98 views

Category:

Documents


0 download

DESCRIPTION

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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 3 Data Types, Variables, and Expressions

CHAPTER 3DATA TYPES, VARIABLES, AND EXPRESSIONS

1

Page 2: 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.• 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

Page 3: Chapter 3 Data Types, Variables, and Expressions

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

Page 4: Chapter 3 Data Types, Variables, and Expressions

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)

Page 5: Chapter 3 Data Types, Variables, and Expressions

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

Page 6: Chapter 3 Data Types, Variables, and Expressions

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?

Page 7: Chapter 3 Data Types, Variables, and 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

Page 8: Chapter 3 Data Types, Variables, and Expressions

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

Page 9: Chapter 3 Data Types, Variables, and Expressions

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.

Page 10: Chapter 3 Data Types, Variables, and Expressions

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

Page 11: Chapter 3 Data Types, Variables, and Expressions

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

Page 12: Chapter 3 Data Types, Variables, and Expressions

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

Page 13: Chapter 3 Data Types, Variables, and Expressions

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.

Page 14: Chapter 3 Data Types, Variables, and Expressions

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

Page 15: Chapter 3 Data Types, Variables, and Expressions

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

Page 16: Chapter 3 Data Types, Variables, and Expressions

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

Page 17: Chapter 3 Data Types, Variables, and Expressions

17

String LiteralA string literal is a sequence ofcharacters surrounded by quotation marks.

Examples:"hello"

"123-45-6789""#ab cde?"

Page 18: Chapter 3 Data Types, Variables, and Expressions

18

String VariableA string variable is a name to which astring value can be assigned.

Examples:countryssnword

firstName

Page 19: Chapter 3 Data Types, Variables, and Expressions

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.

Page 20: Chapter 3 Data Types, Variables, and Expressions

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

Page 21: Chapter 3 Data Types, Variables, and Expressions

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

Page 22: Chapter 3 Data Types, Variables, and Expressions

Appending• To append str to the string variable var

var = var & str

• Or as a shortcutvar &= str

22

Page 23: Chapter 3 Data Types, Variables, and Expressions

Appending ExampleDim var As String = "Good"var &= "bye"

Resulting value in var: Goodbye

23

Page 24: Chapter 3 Data Types, Variables, and Expressions

24

Strings• String Properties and Methods:

Length ToUpperTrim ToLowerIndexOf Substring

Page 25: Chapter 3 Data Types, Variables, and Expressions

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.

Page 26: Chapter 3 Data Types, Variables, and Expressions

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

Page 27: Chapter 3 Data Types, Variables, and Expressions

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

Page 28: Chapter 3 Data Types, Variables, and Expressions

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

Page 29: Chapter 3 Data Types, Variables, and Expressions

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

Page 30: Chapter 3 Data Types, Variables, and Expressions

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

Page 31: Chapter 3 Data Types, Variables, and Expressions

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

Page 32: Chapter 3 Data Types, Variables, and Expressions

Option Strict (continued)

32

Page 33: Chapter 3 Data Types, Variables, and Expressions

33

Auto Correction

Page 34: Chapter 3 Data Types, Variables, and Expressions

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

Page 35: Chapter 3 Data Types, Variables, and Expressions

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

Page 36: Chapter 3 Data Types, Variables, and Expressions

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

Page 37: Chapter 3 Data Types, Variables, and Expressions

37

Three Types of Errors• Syntax error• Runtime error• Logic error

Page 38: Chapter 3 Data Types, Variables, and Expressions

38

Some Types of Syntax Errors• Misspellings lstBox.Itms.Add(3)• Omissions lstBox.Items.Add(2 + )• Incorrect punctuation Dim m; n As Integer

Page 39: Chapter 3 Data Types, Variables, and Expressions

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

39

Page 40: Chapter 3 Data Types, Variables, and Expressions

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.

Page 41: Chapter 3 Data Types, Variables, and Expressions

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

Page 42: Chapter 3 Data Types, Variables, and Expressions

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