computer programming

74
1 Computer Programming Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology [email protected] http://www.cse.dlit.edu.tw/~andres

Upload: jemma

Post on 20-Jan-2016

23 views

Category:

Documents


0 download

DESCRIPTION

Computer Programming. Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology [email protected] http://www.cse.dlit.edu.tw/~andres. Chapter 4 Numeric Types and Expressions. Chapter 4 Topics. Constants of Type Integer and Double - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Computer Programming

1

Computer Programming

Andres, Wen-Yuan Liao

Department of Computer Science and EngineeringDe Lin Institute of Technology

[email protected]://www.cse.dlit.edu.tw/~andres

Page 2: Computer Programming

2

Chapter 4

Numeric Types and Expressions

Page 3: Computer Programming

3

Chapter 4 Topics

Constants of Type Integer and Double Evaluating Arithmetic Expressions Increment and Decrement Operators Implicit Type Conversion and Explicit Type

Casting Calling a Value-Returning Method Using VB .NET Math class methods String Operations Length, IndexOf, Substring

Page 4: Computer Programming

4

4.1 VB .NET Primitive Data Types4.1 VB .NET Primitive Data Types

primitive

Integral

Boolean

Byte Char Short Integer Long Single Double

Floating Point

Page 5: Computer Programming

5

VB .NET Data TypesVB .NET Data Types

Reference

Array Interface Class

primitive

Integral Boolean

Byte Char Short Integer Long Single Double

Floating Point

VB .NET Data Types

Page 6: Computer Programming

6

Primitive and Reference Types

letter

Dim letter As Char

Dim title As String

Dim bookName As String

letter = "J"

title = " Programming with VB.NET "

bookName = title

Page 7: Computer Programming

7

Primitive and Reference Types

letter

title

Dim letter As Char

Dim title As String

Dim bookName As String

letter = "J"

title = " Programming with VB.NET "

bookName = title

Page 8: Computer Programming

8

Primitive and Reference Types

letter

title

bookName

Dim letter As Char

Dim title As String

Dim bookName As String

letter = "J"

title = " Programming with VB.NET "

bookName = title

Page 9: Computer Programming

9

Primitive and Reference Types

letter

title

bookName

Dim letter As Char

Dim title As String

Dim bookName As String

letter = "J"

title = " Programming with VB.NET "

bookName = title

"J"

Page 10: Computer Programming

10

Primitive and Reference Types

letter

title

bookName

2002

"Programming with VB.NET "

Memory Location 2002

"J"

Dim letter As Char

Dim title As String

Dim bookName As String

letter = "J"

title = " Programming with VB.NET "

bookName = title

Page 11: Computer Programming

11

Dim letter As Char

Dim title As String

Dim book As String

letter = "J"

title = " Programming with VB.NET "

book = title

Primitive and Reference Types

letter

title

bookName

2002

2002

"Programming with VB.NET "

Memory Location 2002

"J"

Page 12: Computer Programming

12

Primitive and Reference Types

Dim letter As Char

Dim title As String

Dim book As String

letter = "J"

title = " Programming with VB.NET "

bookName = title

letter

title

bookName

2002

2002

"Programming with VB.NET "

Memory Location 2002

"J"

Page 13: Computer Programming

13

4.2Primitive Data Types in VB .NET

Integral Types can represent whole numbers and their

negatives when declared as Short, Integer, or Long

can represent single characters when declared as Char

Floating Point Types represent real numbers with a decimal point declared as Single, or Double

Page 14: Computer Programming

14

Samples of VB .NET Data Values

Integer sample values 4578 -4578 0

Double sample values95.274 95. .265

Char sample values

‘B’ ‘d’ ‘4’ ‘?’ ‘*’

Page 15: Computer Programming

15

Integral Types

Type Size in Bits Minimum Value to Maximum Value

Byte 8 -128 to 127

Short 16 -32,768 to 32,767

Integer 32 -2,147,483,648 to 2,147,483,647

Long 64 -9,223,372,036,854,775,808 to

+9,223,372,036,854,775,807

Page 16: Computer Programming

16

Sizes of Integral VB .NET Types

Byte 8 bits

Short 16 bits

Integer 32 bits

Long 64 bits

Page 17: Computer Programming

17

Using one byte ( = 8 bits ),

HOW MANY DIFFERENT NUMBERS CAN BE REPRESENTED USING 0’s and 1’s?

Each bit can hold either a 0 or a 1. So there are just two choices for each bit, and there are 8 bits.

2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 = 28 = 256

0 1 1 0 0 0 1 1

Page 18: Computer Programming

18

Similarly, using two bytes (= 16 bits),

216 = 65536

DIFFERENT NUMBERS CAN BE REPRESENTED. If we wish to have only one number representing the

integer zero, and half of the remaining numbers positive, and half negative, we can obtain the 65,536 numbers in the range below :

-32768 . . . . 0 . . . . 32767

0 1 0 0 1 0 1 00 1 1 0 0 0 1 1

Page 19: Computer Programming

19

Exponential (Scientific) Notation

2.7E4 means 2.7 x 10 4 =

2.7000 =

27000.0

2.7E-4 means 2.7 x 10 - 4 =

0002.7 =

0.00027

Page 20: Computer Programming

Type Size in Bits Range of Values

Single 32 +1.4E - 45 to

+3.4028235E+38

Double 64 +4.9E - 324 to

+1.7976931348623157E+308

Floating Point Types

Page 21: Computer Programming

21

More About Floating Point Types

Floating-point types have an integer part and a fractional part, with a decimal point in between. Either the integer part or the fractional part, but not both, may be missing.

EXAMPLES 18.4 500. .8 -127.358

Alternatively, floating point values can have an exponent, as in scientific notation. The number preceding the letter E doesn’t need to include a decimal point.

EXAMPLES 1.84E1 5E2 8E-1 -.127358E3

Page 22: Computer Programming

22

4.3 Declarations for Numeric Types

Named constant declarationConst PI As Double =3.14159

Const E As Single = 2.71828F

Const MAX_TEMP As Long = 1000000000L

Const MIN_TEMP As Integer = -273

Page 23: Computer Programming

23

Variable Declarations

Dim student As Integer

Dim sumOfScore As Integer

Dim sumOfSquare As Long

Dim average As Double

Dim deviation As Simgle

Page 24: Computer Programming

24

4.4 What is an Arithmetic Expression?

An arithmetic expression is a valid arrangement of variables, constants, operators and parentheses.

An expression can be evaluated to compute a value of a given type.

The value of the expression

9.3 * 4.5 is 41.85

Page 25: Computer Programming

25

Some VB .NET Operators

Operator Description ( ) Parentheses

+ Positive

- Negative

* Multiplication

/ Division % Modulus

(remainder)

+ Addition

- Subtraction

= Assignment

Page 26: Computer Programming

26

Operator

Operand, operator Unary operator

An operator that has just one operand. + (positive), -(negative)

Binary operator An operator that has two operand. + (Addition), - (Subtraction), *, /, %, =

Page 27: Computer Programming

27

Division Operator

The result of the division operator depends on the type of its operands.

If one or both operands has a floating type, the result is a floating point type (float or double). Otherwise, the result is an integral type.

EXAMPLES

11 / 4 has value 2

11.0 / 4.0 has value 2.75

11 / 4.0 has value 2.75

Page 28: Computer Programming

28

Modulus Operator

The modulus operator % when used with integer type operands has an integer type result.

Its result is the integer type remainder of an

integer division.

EXAMPLE

11 % 4 has value 3 because

)4 11

2 and Remainder = ?

Page 29: Computer Programming

29

' *************************************************' FreezeBoil program' This program computes the midpoint between' the freezing and boiling points of water' *************************************************

Imports System.ComponentModel 'Import component handlingImports System.Drawing 'Import graphicsImports System.WinForms 'Import forms, event

'handling types

Public Class Form1 'Create form for output Inherits System.WinForms.Form Const FREEZE_PT As Double = 32 'Freezing pt of water Const BOIL_PT As Double = 212 'Boiling pt of water Dim avgTemp As Double 'Holds the result of

'averaging FREEZE_PT and'BOIL_PT

Public Sub New() MyBase.New()

Form1 = Me

Page 30: Computer Programming

30

'This call is required by the Win Form Designer InitializeComponent() lblFreeze.Text = "Water freezes at " & FREEZE_PT lblFreeze.text = lblFreeze.Text & " and boils at “ & _

BOIL_PT & " degrees." avgTemp = FREEZE_PT + BOIL_PT avgTemp = avgTemp / 2

lblFreeze.Text = lblFreeze.Text & "Halfway between is"_& avgTemp & "degrees."

Page 31: Computer Programming

31

4.5 Compound VB .NET Operators

Precedence Operator Description Higher ( ) Parentheses

+ Positive

- Negative

* Multiplication

/ Division % Modulus

(remainder)

+ Addition

- Subtraction

Lower = Assignment

Page 32: Computer Programming

32

Precedence

Higher Precedence determines which

operator is applied first in an expression

having several operators.

Page 33: Computer Programming

33

Associativity

Left to right Associativity means that in an expression having 2 operators with the same priority, the left operator is applied first. (left to right)

In VB .NET, the binary operators * , / , % , + , - are all left associative.

Expression 9 - 5 + 1 means ( 9 - 5 ) + 1not 9 – (5 +1 ) 4 + 1

5

Page 34: Computer Programming

34

VB .NET Operator Precedence(highest to lowest)

Operator Associativity

. ( ) ( args ) Left to right

unary: + - Right to left

New ( type ) Right to left

* / % Left to right

+ - Left to right

= Right to left

Page 35: Computer Programming

35

7 * 10 - 5 % 3 * 4 + 9means (7 * 10) - 5 % 3 * 4 + 9

70 - 5 % 3 * 4 + 9 70 - (5 % 3) * 4 + 9

70 - 2 * 4 + 9 70 - ( 2 * 4 ) + 9 70 - 8 + 9

( 70 - 8 ) + 9 62 + 9

71

Evaluate the Expression

Page 36: Computer Programming

36

Parentheses

Parentheses can be used to change the usual order. Parts in ( ) are evaluated first. Evaluate (7 * (10 - 5) % 3) * 4 + 9

( 7 * 5 % 3 ) * 4 + 9 ( 35 % 3 ) * 4 + 9

2 * 4 + 9 8 + 9

17

Page 37: Computer Programming

37

More VB .NET Operators

Dim age As Integer

age = 8

age = age + 1

age

9

8

age

Page 38: Computer Programming

38

Variable = Expression

First, Expression on right is evaluated.

Then the resulting value is stored in the memory location of Variable on left.

NOTE: An automatic type conversion occurs after evaluation but before the value is stored if the types differ for Expression and Variable

Assignment Operator Syntax

Page 39: Computer Programming

39

What value is stored?

Dim a As Double

Dim b As Double

a = 8.5

b = 9.37

a = b

a

b

a

b

8.5

9.37

?

?

Page 40: Computer Programming

40

What value is stored?

Dim a As Double

Dim b As Double

a = 8.5

b = 9.37

a = b

a

b

a

b

8.5

9.37

9.37

9.37

Page 41: Computer Programming

41

What is stored?

?

Dim someDouble As Single

someDouble = 12 ' implicit type conversion

someDouble

12.0

someDouble

Page 42: Computer Programming

42

What is stored?

? Dim someInt As Integer

someInt someInt = 4.8 ' implicit type conversion

someInt

4

Page 43: Computer Programming

43

Implicit type conversion occurs . . .

Whenever values of different data types are used in:

1. arithmetic expressions

2. assignment operations

TWO RULES APPLY . . .

Page 44: Computer Programming

44

Type conversion

The implicit (automatic) conversion of a value from one data type to another.

Widening conversion A type conversion that dose not result in a loss of

information.

narrowing conversion A type conversion that may result in a loss of some

information, as in converting a value of type Double to Single.

Page 45: Computer Programming

45

A widening conversion . . .

Is a type conversion that does not result in a loss of information. Specifically, for mixed type expressions using both integer and floating-point type values:

Step 1. The integer value is temporarily converted to a

floating-point value.

Step 2. The operation is performed.

Step 3. The result is a floating-point value.

Page 46: Computer Programming

46

Is a type conversion that may result in a loss of information.

FOR EXAMPLE, 98.6 98

temperature number

Dim temperature As Double = 98.6

Dim number As Integer

number = temperature 'loss occurs

A narrowing conversion . . .

Page 47: Computer Programming

47

CInt converts its argument to an Integer type.

CLng converts its argument to a Long type.

CSng converts its argument to a Single type.

CDbl converts its argument to a Double type.

Type Conversation is Explicit Conversion of Type

Page 48: Computer Programming

48

CInt(4.8) has value 4

CDbl(5) has value 5.0

CDbl(7/4) has value 1.0

CDbl(7) / CDbl(4) has value 1.75

Type Conversation is Explicit Conversion of Type

Page 49: Computer Programming

49

Some Expressions

Dim age As Integer

EXAMPLE

someDouble = CDbl(3 * someInt + 2)

someInt = CInt(5.2 / someDouble – 2.0)

someSingle = someInt + 8

someSingle = CSng( someInt + 8 ) CDbl ( 4 / 8 ) 0.0

CDbl ( 4 ) / 8 0.5

Page 50: Computer Programming

50

What values are stored?

Dim loCost As Double

Dim hiCost As Double

loCost = 12.342

hiCost = 12.348

loCost = CDbl (CInt (loCost * 100.0 + 0.5)) / 100.0

hiCost = CDbl (CInt (hiCost * 100.0 + 0.5)) / 100.0

Page 51: Computer Programming

51

Values Rounded to 2 Decimal Places

12.34

hiCost

12.35

loCost

Page 52: Computer Programming

52

4.6 Method Call

A method call temporarily transfers control to the called method’s code to perform a task.

When the method’s code has finished executing, control is transferred back to the calling block.

Page 53: Computer Programming

53

Where are VB .NET methods?

located in class libraries

OR

written by programmers

Page 54: Computer Programming

54

Write a VB .NET expression . . .

To find the larger of myAge and yourAge and place it in variable older

Dim older As Integer

Page 55: Computer Programming

55

Write a VB .NET expression . . .

To find the larger of myAge and yourAge and place it in variable older

Dim older As Integer

. . .

older = Math.Max ( myAge, yourAge )

Page 56: Computer Programming

56

Write a VB .NET expression . . .

To find the square root of b2 - 4ac and place it in variable d.

Dim a, b, c, d As Double

Page 57: Computer Programming

57

Write a VB .NET expression . . .

To find the square root of b2 - 4ac and place it in variable d.

Dim a, b, c, d As Double

. . .

d = Math.Sqrt ( b * b - 4.0 * a * c )

Page 58: Computer Programming

58

Some Math class methods

Math.Abs ( x ) Math.Abs( -9.8 ) is 9.8' absolute value of x

Math.Sqrt( x ) Math.Sqrt( 9.0 ) is 3.0' square root of a non-negative x

Math.Log ( x ) Math.Log( 1.0 ) is 0' natural (base e) logarithm of x

Math.Max ( x, y ) Math.Max( 2.5, 6.7) is 6.7

' larger value of x and y

Math.Pow ( x, y ) Math.Pow( 9, 0.5 ) is 3.0' x raised to the power y

Page 59: Computer Programming

A method call uses the name of the method followed by ( ) enclosing a list of parameters.

Console.WriteLine ("Done")

older = Math.Max (myAge, your Age)

number = Math.Sqrt (456.34)

A method call temporarily transfers control to the called method to perform its task.

Method Calls

Page 60: Computer Programming

Two Kinds of Methods

Always is called as part of an expression. Does some task.

Returns a value that takes its place in the expression.

Always is called as a separate statement.

Does some task.

Never returns a value to its caller.

Value-Returning Non-value Returning

Page 61: Computer Programming

61

ObjectName.MethodName( Parameter List )

The parameter list is used to communicate values to the method by passing information.

The parameter list can contain 0, 1, or more parameters, separated by commas, depending on the method.

Method Call Syntax

Page 62: Computer Programming

62

4.7 Additional String Operations

Length method Method Length returns an Integer

value that equals the number of characters in the string.

You must use dot notation and parentheses in the call to method Length.

Page 63: Computer Programming

63

What value is returned?

' Using methods Length

Dim firstName As String

Dim fullName As StringDim len As Ineger

firstName = " Alexandra “len = firstName.Length( ) fullName = firstName & “Jones”len = fullName.Length( )

Page 64: Computer Programming

64

IndexOf method

Method IndexOf searches a string to find a

particular substring, and returns an Integer value that is the beginning position for the first

occurrence of that substring within the string.

The substring argument can be a literal String,

a String expression, or a Char value.

If the substring could not be not found, method IndexOf returns value -1.

Page 65: Computer Programming

65

What value is returned?

' Using methods IndexOf

Dim phrase As String Dim position As Integer phrase = “The dog and the cat "

position = phrase.IndexOf(“the” ) position = phrase.IndexOf(“rat” )

Dim theString As String theString = “Abracadaba "

position = theString.IndexOf(“a”c )

Page 66: Computer Programming

66

What value is returned?

' Using methods IndexOf

Dim str1 As String Dim str2 As String str1 = “Programming and Problem Solving "str2 = “gram"

str1.IndexOf(“and” ) str1.IndexOf(“Programming” ) str2.IndexOf(“and” ) str1.IndexOf(“Pro” ) str1.IndexOf(“ro” & str2 ) str1.IndexOf(“pr” & str2 ) str1.IndexOf(“ ” )

Page 67: Computer Programming

67

Substring method

Method Substring returns a particular substring of a string, but does not change the string itself.

The first parameter is an Integer that specifies a starting position within the string.

The second parameter is an Integer that is 1 more than the ending position of the substring.

Positions of characters within a string are numbered starting from 0, not from 1.

Page 68: Computer Programming

68

What value is returned?

' Using methods Length, IndexOf, Substring

Dim myString As String = "Programming and Problem Solving "

myString.Substring ( 0, 7) myString.Substring ( 7, 8) myString.Substring ( 11, 1)

myString.Substring ( 24, 7)myString.Substring ( 24, 1)

Page 69: Computer Programming

69

What value is returned?

' Using methods Length, IndexOf, Substring

Dim stateName As String = " Mississippi "

stateName.Length( ) value 11

stateName.IndexOf ( " is ") value 1

stateName.Substring( 0, 4 ) value “Miss”

stateName.Substring( 4, 6 ) value “is”

stateName.Substring( 9, 11 ) value “pi”

Page 70: Computer Programming

70

Map Measurement Case Study

You want a program to determine walking distances between 4 sights in the city.

Your city map legend says one inch on the map equals 1/4 mile in the city.

You use the measured distances between 4 sights on the map.

Display the walking distances (rounded to the nearest tenth) between each of the 4 sights.

Page 71: Computer Programming

71

'******************************************************* ' Walk program' This program computes the mileage (rounded to nearest' tenth of mile) for each of 4 distances, given the' measurements on a map with scale of 1 in = 0.25 mile' *******************************************************

Imports System.ComponentModelImports System.DrawingImports System.WinForms

Public Class Form1Inherits System.WinForms.Form

VB .NET Case Study Program

Page 72: Computer Programming

72

VB .NET Case Study Continued

Const DISTANCE1 As Double = 1.5 ‘Measurement for 1st distance Const DISTANCE2 As Double = 2.3 'Measurement for 2nd distance Const DISTANCE3 As Double = 5.9 'Measurement for 3rd distance Const DISTANCE4 As Double = 4R 'Measurement for 4th distance Const MAP_SCALE As Double = 0.25 'Map SCALE

Dim totMiles As Double 'Total of rounded mileage Dim miles As Double 'An individual rounded mileage

Public Sub New()My Base.NewForm1 = MeInitializeComponent()

totMiles = 0R

Page 73: Computer Programming

73

'Compute and display miles for each distance on the map'Output will not display .0 amounts

miles = CDbl(CInt(DISTANCE1 * MAP_SCALE * 10R + 0.5) / 10R) lblDistance1.Text = "For a measurement of " & DISTANCE1 & _

" the first distance is " & miles _ & " mile(s) long. "

totMiles = totMiles + miles miles = CDbl(CInt(DISTANCE2 * MAP_SCALE * 10R + 0.5) / 10R) lblDistance2.Text = "For a measurement of " & DISTANCE2 & _

" the second distance is " & miles & _ " mile(s) long."

totMiles = totMiles + miles miles = CDbl(CInt(DISTANCE3 * MAP_SCALE * 10R + 0.5) / 10R) lblDistance3.Text = "For a measurement of " & DISTANCE2 & _

" the second distance is " & miles & _ " mile(s) long."

Page 74: Computer Programming

74

totMiles = totMiles + miles miles = CDbl(CInt(DISTANCE4 * MAP_SCALE * 10R + 0.5) / 10R) lblDistance4.Text = "For a measurement of " & DISTANCE2 & _

" the second distance is " & miles & _ " mile(s) long."

totMiles = totMiles + miles lblTotMiles.Text = "Total mileage for the day is " & _

totMiles & " miles." End Sub

'Form overrides dispose to clean up the component list. Overrides Public Sub Dispose()

MyBase.Disposecomponents.Dispose

End Sub

#Region " Windows Form Designer generated code "

#End Region

End Class