Deeper Look Pearson Education, Inc. All rights reserved.

Size: px
Start display at page:

Download "Deeper Look Pearson Education, Inc. All rights reserved."

Transcription

1 1 7 Methods: A Deeper Look

2 2 The greatest invention of the nineteenth century was the invention of the method of invention. Alfred North Whitehead ead Form ever follows function. Louis Henri Sullivan Call me Ishmael. Herman Melville, Moby Dick When you call me that, smile! Owen Wister

3 3 O! call back yesterday, bid time return. William Shakespeare Answer me in one word. William Shakespeare There is a point at which methods devour themselves. Frantz Fanon

4 4 OBJECTIVES In this chapter you will learn: To construct t programs modularly l from methods. That Shared methods are associated with a class rather than a specific instance of the class. To use common Math methods from the Framework Class Library. To create new methods.

5 5 OBJECTIVES The mechanisms used to pass information between methods. Simulation techniques that employ random number generation. How the visibility of identifiers is limited to specific regions of programs. To write and use recursive methods (methods that call themselves).

6 6 7.1 Introduction 7.2 Modules, Classes and Methods 7.3 Subroutines: Methods That Do Not Return a Value Functions: Methods That Return a Value 7.5 Shared Methods and Class Math 7.6 GradeBook Case Study: Declaring Methods with Multiple l Parameters 7.7 Notes on Declaring and Using Methods 7.8 Method Call Stack and Activation Records 7.9 Implicit Argument Conversions 7.10 Option Strict and Data-Type Conversions

7 Value Types and Reference Types 7.12 Framework Class Library Namespaces 7.13 Passing Arguments: Pass-by-Value vs. Pass-by-Reference 7.14 Scope of Declarations 7.15 Case Study: Random Number Generation 7.16 Case Study: A Game of Chance 7.17 Method Overloading 7.18 Optional Parameters 7.19 Recursion 7.20 (Optional) Software Engineering Case Study: Identifying i Class Operations in the ATM System

8 7.2 Modules, Classes and Methods 8 Programs consist of many pieces, including modules and classes. Modules and classes are composed of methods, fields and properties. You combine new modules and classes with those available in class libraries. Related classes are grouped into namespaces.

9 7.2 Modules, Classes and Methods (Cont.) 9 Software Engineering Observation 7.1 When possible, use.net Framework classes and methods instead of writing new classes and methods. This reduces program development time and can prevent the introduction of errors. Performance Tip 7.1.NET Framework Class Library methods are written to perform efficiently.

10 7.2 Modules, Classes and Methods (Cont.) 10 A method is invoked by a method call. The method call specifies the method name and provides information. When the method completes its task, it returns control to the caller. In some cases, the method also returns a result to the caller.

11 7.2 Modules, Classes and Methods (Cont.) 11 A boss (the caller) asks a worker (the callee) to perform a task and return the results when the task is done. The worker might call other workers the boss would be unaware of this (Fig. 71) 7.1). Fig. 7.1 Hierarchical boss-method/worker-method relationship.

12 7.2 Modules, Classes and Methods (Cont.) 12 Software Engineering Observation 7.2 To promote reusability, the capabilities of each method should be limited to the performance of a single, well-defined task, and the name of the method should express that task effectively. Software Engineering Observation 7.3 If you cannot choose a concise method name that expresses the task performed by a method, the method could be attempting to perform too many diverse tasks. Consider dividing such a method into several smaller methods.

13 Subroutines (such as Console.WriteLine) do not return a value. The console application in Fig. 7.2 uses a subroutine to print a worker s payment information. Outline Payment.vb (1 of 2 ) 13 1 ' Fig. 7.2: Payment.vb 2 ' Subroutine that prints payment information. 3 Module Payment 4 Sub Main() 5 ' call subroutine PrintPay 4 times 6 PrintPay(40, 10.5) 7 PrintPay(38, 21.75) Main makes four calls to the 8 PrintPay(20, 13) subroutine PrintPay. 9 PrintPay(30, 14) 10 End Sub ' Main Fig. 7.2 Subroutine for printing payment information. (Part 1 of 2.) 2009 Pearson Education, Inc. All rights reserved.

14 Outline 14 Payment.vb (2 of 2 ) ' print dollar amount earned in console window 13 Sub PrintPay(ByVal hours As Double, ByVal wage As Decimal) 14 ' pay = hours * wage 15 Console.WriteLine("The i payment is {0:C}", hours * wage) 16 End Sub ' PrintPay 17 End Module ' Payment Method PrintPay is a subroutine. The payment is $ The payment is $ The payment is $ The payment is $ Fig. 7.2 Subroutine for printing payment information. (Part 2 of 2.) 2009 Pearson Education, Inc. All rights reserved.

15 7.3 Subroutines: Methods That Do Not Return a Value (Cont.) 15 The format of a subroutine declaration is: Sub method-name(parameter-list) declarations and statements End Sub The parameter-list is a comma-separated list of each parameter s type and name. The type of each argument must be consistent with its corresponding parameter s a type. If a method does not receive any values, the method name is followed by an empty set of parentheses.

16 7.3 Subroutines: Methods That Do Not Return a Value (Cont.) Common Programming Error 7.1 Declaring a variable in the method s body with the same name as a parameter variable in the method header is a compilation error. 16 Error-Prevention Tip 7.1 Although it is allowable, an argument passed to a method should not have the same name as the corresponding parameter name in the method declaration. This prevents ambiguity that could lead to logic errors.

17 7.3 Subroutines: Methods That Do Not Return a Value (Cont.) 17 The method body (also referred to as a block) contains declarations and statements. t t The body of a method declared with Sub must be terminated with End Sub. Software Engineering Observation 7.4 Method names tend to be verbs because methods typically perform actions. By convention, method names begin with an uppercase first letter. For example, a method that sends an message might be named SendMail.

18 7.3 Subroutines: Methods That Do Not Return a Value (Cont.) Error-Prevention Tip 7.2 Small methods are easier to test, debug and understand than large methods. 18 Good Programming Practice 7.1 When a parameter is declared without a type, its type is assumed to be Object. Explicitly declaring a parameter s type improves program clarity.

19 Outline 19 Functions are methods that return a value to the caller. The console application in Fig. 7.3 uses the function Square to calculate the squares of the integers from SquareInteger.vb (1 of 2 ) 1 ' Fig. 7.3: SquareInteger.vb 2 ' Function that squares a number. 3 Module SquareInteger 4 Sub Main() 5 Console.WriteLine("Number" & vbtab & "Square") 6 7 ' square integers from 1 to 10 8 For counter = 1 To 10 The For Next statement 9 Console.WriteLine(counter & vbtab & Square(counter)) displays the results 10 Next 11 End Sub ' Main of squaring the integers. Fig. 7.3 Function for squaring an integer. (Part 1 of 2.) 2009 Pearson Education, Inc. All rights reserved.

20 Outline 20 SquareInteger.vb (2 of 2 ) ' function Square is executed when it is explicitly called 14 Function Square(ByVal y As Integer) As Integer 15 Return y ^ 2 ' return square of parameter value 16 End Function ' Square 17 End Module ' SquareInteger Number Square Square receives a copy of counter s value. The Return statement terminates the method and returns the result. Fig. 7.3 Function for squaring an integer. (Part 2 of 2.) 2009 Pearson Education, Inc. All rights reserved.

21 7.4 Functions: Methods That Return a Value (Cont.) 21 The Return statement terminates the method and returns the result. The return statement can occur anywhere in a function body. Return expression The return-type indicates the type of the result returned from the function.

22 7.4 Functions: Methods That Return a Value (Cont.) Common Programming Error 7.2 If the expression in a Return statement cannot be converted to the function s return-type, a run-time error is generated. 22 Common Programming Error 7.3 Failure to return a value from a function (e.g., by forgetting to provide a Return statement) causes the function to return the default value for the return-type, possibly producing incorrect output. t

23 7.5 Shared Methods and Class Math 23 A method which performs a task that does not depend on an object is known as a Shared method. Place the Shared modifier before the keyword Sub or Function. To call a Shared method: ClassName.MethodName(arguments) Class Math provides a collection of Shared methods: Math.Sqrt(900.0)

24 7.5 Shared Methods and Class Math (Cont.) Software Engineering Observation 7.5 It is not necessary to add an assembly reference to use the Math class methods in a program, because class Math is located in the assembly mscorlib.dll, which is referenced by every.net application. Also it is not necessary to import class Math s namespace (System), because it is implicitly imported in all.net applications. 24

25 7.5 Shared Methods and Class Math (Cont.) 25 Figure 7.4 summarizes several Math class methods. In the figure, x and y are of type Double. Method Description Example Abs(x) returns the absolute value of x Abs(23.7) is 23.7 Abs(0) is 0 Abs(-23.7) is 23.7 Ceiling(x) rounds x to the smallest integer not Ceiling(9.2) is 10.0 less than x Ceiling(-9.8) is -9.0 Cos(x) returns the trigonometric cosine of x (x in radians) Cos(0.0) is 1.0 Exp(x) returns the exponential e x Exp(1.0) is approximately Exp(2.0) is approximately Fig. 7.4 Math class methods. (Part 1 of 3.)

26 7.5 Shared Methods and Class Math (Cont.) 26 Method Description Example Floor(x) Log(x) rounds x to the closets integer less than or equal to x returns the natural logarithm of x (base e) Floor(9.2) is 9.0 Floor(-9.8) is Log( ) is approximately 1.0 Log( ) is approximately 2.0 Max(x, y) returns the larger value of x and y Max(2.3, 12.7) is 12.7 Max(-2.3, -12.7) is -2.3 Min(x, y) returns the smaller value of x and y Min(2.3, 12.7) is 2.3 Min(-2.3, -12.7) is Fig. 7.4 Math class methods. (Part 2 of 3.)

27 7.5 Shared Methods and Class Math (Cont.) 27 Method Description Example Pow(x, y) calculates x raised to the power y (x y ) Pow(2.0, 7.0) is Pow(9.0,.5) is 3.0 Sin(x) returns the trigonometric sine of x (x in radians) Sin(0.0) is 0.0 Sqrt(x) returns the square root of x Sqrt(9.0) is 3.0 Sqrt(2.0) is Tan(x) returns the trigonometric tangent of x (x in radians) Tan(0.0) is 0.0 Fig. 7.4 Math class methods. (Part 3 of 3.)

28 7.5 Shared Methods and Class Math (Cont.) 28 Math.PI and Math.E are declared in class Math with ihthe modifiers Public and Const. Const declares a constant a value that cannot be changed. Constants are implicitly Shared.

29 Outline 29 The application in Figs uses a user-declared method called Maximum to GradeBook.vb determine the largest of three Integer values. 1 ' Fig. 7.5: GradeBook.vb 2 ' Definition of class GradeBook that finds the maximum of three grades. 3 Public Class GradeBook 4 Private coursenamevalue As String ' name of course 5 Private maximumgrade As Integer ' maximum of three grades 6 7 ' constructor initializes course name 8 Public Sub New(ByVal name As String) 9 CourseName = name ' initializes CourseName 10 maximumgrade = 0 ' this value will be replaced by maximum grade 11 End Sub ' New 12 (1 of 5 ) Fig. 7.5 User-declared method Maximum that has three Integer parameters. (Part 1 of 5.) 2009 Pearson Education, Inc. All rights reserved.

30 Outline ' property that gets and sets the course name; the Set accessor 14 ' ensures that the course name has at most 25 characters 15 Public Property CourseName() As String 16 Get ' retrieve coursenamevalue 17 Return coursenamevalue 18 End Get Set(ByVal value As String) ' set coursenamevalue 21 If value.length <= 25 Then ' if value has 25 or fewer characters 22 coursenamevalue = value ' store the course name in the object 23 Else ' if name has more than 25 characters 24 ' set coursenamevalue to first 25 characters of parameter name 25 ' start at 0, length of coursenamevalue = value.substring(0, 25) Console.WriteLine( _ 29 "Course name (" & value & ") exceeds maximum length (25).") 30 Console.WriteLine( _ 31 "Limiting course name to first 25 characters. " & vbnewline) 32 End If 33 End Set 34 End Property ' CourseName GradeBook.vb (2 of 5 ) Fig. 7.5 User-declared method Maximum that has three Integer parameters. (Part 2 of 5.) 2009 Pearson Education, Inc. All rights reserved.

31 Outline ' display a welcome message to the GradeBook user 37 Public Sub DisplayMessage() 38 Console.WriteLine("Welcome to the grade book for " _ 39 & vbnewline & CourseName & "!" & vbnewline) 40 End Sub ' DisplayMessage ' input three grades from user 43 Public Sub InputGrades() 44 Dim grade1 As Integer ' first grade entered by user 45 Dim grade2 As Integer ' second grade entered by user 46 Dim grade3 As Integer ' third grade entered by user Console.Write("Enter the first grade: ") 49 grade1 = Console.ReadLine() 50 Console.Write("Enter the second grade: ") 51 grade2 = Console.ReadLine() 52 Console.Write("Enter the third grade: ") 53 grade3 = Console.ReadLine() ' store the maximum in maximumgrade 56 maximumgrade = Maximum(grade1, grade2, grade3) 57 End Sub ' InputGrades GradeBook.vb (3 of 5 ) Fig. 7.5 User-declared method Maximum that has three Integer parameters. (Part 3 of 5.) 2009 Pearson Education, Inc. All rights reserved.

32 Outline ' returns the maximum of its three integer parameters 60 Function Maximum(ByVal x As Integer, ByVal y As Integer, _ 61 ByVal z As Integer) As Integer Dim maximumvalue As Integer = x ' assume x is the largest to start ' determine whether y is greater than maximumvalue 66 If (y > maximumvalue) Then 67 maximumvalue = y ' make y the new maximumvalue 68 End If 69 GradeBook.vb (4 of 5 ) Fig. 7.5 User-declared method Maximum that has three Integer parameters. (Part 4 of 5.) 2009 Pearson Education, Inc. All rights reserved.

33 Outline ' determine whether z is greater than maximumvalue 71 If (z > maximumvalue) Then 72 maximumvalue = z ' make z the new maximumvalue 73 End If Return maximumvalue 76 End Function ' Maximum ' display a report based on the grades entered by user 79 Public Sub DisplayGradeReport() 80 ' output maximum of grades entered 81 Console.WriteLine("Maximum of grades entered: " & maximumgrade) 82 End Sub ' DisplayGradeReport p 83 End Class ' GradeBook GradeBook.vb (5 of 5 ) Fig. 7.5 User-declared method Maximum that has three Integer parameters. (Part 5 of 5.) 2009 Pearson Education, Inc. All rights reserved.

34 Outline 34 1 ' Fig. 7.6: GradeBookTest.vb 2 ' Create a GradeBook object, input grades and display grade report. 3 Module GradeBookTest 4 Sub Main() 5 ' create GradeBook object 6 Dim gradebook1 As New GradeBook("CS101 Introduction to VB") 7 8 gradebook1.displaymessage() ' display welcome message 9 gradebook1.inputgrades() ' read grades from user 10 gradebook1.displaygradereport() ' display report based on grades 11 End Sub ' Main 12 End Module ' GradeBookTest GradeBookTest.vb (1 of 2 ) Welcome to the grade book for CS101 Introduction to VB! Enter the first grade: 65 Enter the second grade: 87 Enter the third grade: 45 Maximum of grades entered: 87 (continued on next page...) Fig. 7.6 Application to test class GradeBook s Maximum method. (Part 1 of 2.) 2009 Pearson Education, Inc. All rights reserved.

35 Outline 35 Welcome to the grade book for CS101 Introduction to VB! Enter the first grade: 45 Enter the second grade: 65 Enter the third grade: 87 Maximum of grades entered: 87 (continued from previous page ) GradeBookTest.vb (2 of 2 ) Welcome to the grade book for CS101 Introduction to VB! Enter the first grade: 87 Enter the second grade: 45 Enter the third grade: 65 Maximum of grades entered: 87 Fig. 7.6 Application to test class GradeBook s Maximum method. (Part 2 of 2.) 2009 Pearson Education, Inc. All rights reserved.

36 7.7 Notes on Declaring and Using Methods 36 There are three ways to call a method: Using a method name by itself within the same class or module. Using a reference to an object, followed by a dot (.) and the method name to call a method of the object. Using the class or module name and a dot (.) to call a Shared method. A Shared method can call only other Shared methods.

37 7.7 Notes on Declaring and Using Methods (Cont.) Common Programming Error 7.4 Declaring a method outside the body of a class or module declaration or inside the body of another method is a syntax error. Common Programming Error 7.5 Omitting the return-value-type in a method declaration, if that method is a function, is a syntax error. Common Programming Error 7.6 Redeclaring a method parameter as a local variable in the method s body is a compilation error. Common Programming Error 7.7 Returning a value from a method that is a subroutine is a compilation error. 37

38 7.8 Method Call Stack and Activation Records 38 A data structure known as a stack is analogous to a pile of fdishes. When a dish is placed on the pile, it is placed at the top (pushing onto the stack). When a dish is removed from the pile, it is removed from the top (popping off the stack). Stacks are known as last-in, first-out (LIFO) data structures.

39 7.8 Method Call Stack and Activation Records (Cont.) 39 When a program calls a method, the return address of the caller is pushed onto the method call stack. Successive return addresses are pushed onto the stack. The memory for the local variables in each method is in the activation record or stack frame. When the method returns to its caller, the activation record is popped off the stack. If too many method calls occur then stack overflow occurs.

40 7.9 Implicit Argument Conversions 40 An important feature of argument passing is implicit argument conversion. A widening conversion occurs when an argument is converted to another type that can hold more data. A narrowing conversion occurs when there is potential for data loss during the conversion.

41 7.9 Implicit Argument Conversions (Cont.) 41 Figure 7.7 lists the widening conversions supported by Visual Basic. Type Boolean Byte Char Date Decimal Double Integer Long Conversion types no possible widening conversions to other primitive types UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single or Double String no possible widening conversions to other primitive types Single or Double no possible widening conversions to other primitive types Long, Decimal, Single or Double Decimal, Single or Double Fig. 7.7 Widening conversions between primitive types. (Part 1 of 2.)

42 7.9 Implicit Argument Conversions (Cont.) 42 Type SByte Short Single String UInteger ULong UShort Conversion types Short, Integer, Long, Decimal, Single or Double Integer, Long, Decimal, Single or Double Double no possible widening conversions to other primitive types ULong, Long, Decimal, Single or Double Decimal, Single or Double UInteger, Integer, ULong, Long, Decimal, Single or Double Fig. 7.7 Widening conversions between primitive types. (Part 2 of 2.)

43 7.9 Implicit Argument Conversions (Cont.) 43 Common Programming Error 7.8 Converting a primitive-type type value to a value of another primitive type may change the value if the conversion is not a widening conversion. For example, converting a floating-point value to an integral value truncates any fractional part of the floating-point value (e.g., 4.7 becomes 4).

44 7.9 Implicit Argument Conversions (Cont.) 44 Conversions occur in expressions containing two or more types. Temporary copies of the values are converted to the widest t type in the expression. The value of integernumber is converted to type Single for this operation: singlenumber + integernumber

45 7.10 Option Strict and Data-Type Conversions Option Explicit forces an explicit declaration of variables before they are used. To set Option Explicit to Off, double click My Project in Solution Explorer (Fig. 7.8). Click the Compile tab, then select the value Off from the Option Explicit drop-down list. Compile tab Drop-down list to modify Option Explicit Drop-down list to modify Option Strict Drop-down list to modify Option Infer 45 Fig. 7.8 Modifying Option Strict and Option Explicit.

46 7.10 Option Strict and Data-Type Conversions (Cont.) 46 Option Strict requires explicit conversion for all narrowing conversions. An explicit conversion uses a cast operator or a method. The methods of class Convert explicitly convert data from one type to another: number = Convert.ToDouble(Console.ReadLine())

47 7.10 Option Strict and Data-Type Conversions (Cont.) 47 Option Infer enables the compiler to infer a variable s ibl type based on its initializer i i value. You can set the default values of Option Explicit, Option Strict t and Option Infer. Select Tools > Options... Under Projects and Solutions, select VB Defaults Choose the appropriate value in each option s ComboBox. Error-Prevention Tip 7.3 From this point forward, all code examples have Option Strict set tto On.

48 7.11 Value Types and Reference Types 48 All Visual Basic types can be categorized as either value types or reference types. A variable of a value type contains data of that type. A variable of a reference e e type contains the address of the location in memory where the data is stored.

49 7.11 Value Types and Reference Types (Cont.) 49 Type Size in bits Values Standard Name of.net class or structure Boolean True or False Boolean Byte 8 0 to 255 Byte SByte to 127 SByte Char 16 One Unicode character (Unicode character set) Date 64 1 January 0001 to 31 December :00:00 AM to 11:59:59 PM Char DateTime Decimal E-28 to 7.9E+28 Decimal Fig. 7.9 Primitive types. (Part 1 of 3.)

50 7.11 Value Types and Reference Types (Cont.) 50 Type Size in bits Values Standard Name of.net class or structure Double 64 ±5.0E 324 to ±1.7E+308 (IEEE 754 Double floating point) 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 Int32 Int64 Short 16 32,768 to 32,767 Int16 Single 32 ±1.5E-45 to ±3.4E+38 (IEEE 754 Single floating point) Fig. 7.9 Primitive types. (Part 2 of 3.)

51 7.11 Value Types and Reference Types (Cont.) 51 Size Name of in.net class Type bits Values Standard or structure re String 0 to ~ Unicode characters (Unicode character set) String UInteger 32 0 to 4,294,967,295 UInt32 ULong 64 0 to 18,446,744,073,709,551,615 UInt64 UShort 16 0 to 65,535 UInt16 Fig. 7.9 Primitive types. (Part 3 of 3.)

52 7.12 Framework Class Library Namespaces 52 The.NET framework contains many classes grouped into over 100 namespaces. A program includes the an Imports declaration to use classes from that namespace: Imports System.Windows.Forms

53 7.12 Framework Class Library Namespaces (Cont.) 53 Some key namespaces are described in Fig Namespace Description System.Windows.Forms Contains the classes required to create and manipulate GUIs. System.IO System.Data System.Web System.Xml Contains classes that enable programs to input and output data. Contains classes that enable programs to access and manipulate databases (i.e., an organized collection of data). Contains classes used for creating and maintaining Web applications, which are accessible over the Internet. Contains classes for creating and manipulating XML data. Data can be read from or written to XML files. Fig NET Framework Class Library namespaces (a subset). (Part 1 of 2.)

54 7.12 Framework Class Library Namespaces (Cont.) 54 Namespace System.Collections System.Net System.Text System.Threading System.Drawing Description Contains classes that define data structures for maintaining collections of data. Contains classes that enable programs to communicate via computer networks like the Internet. Contains classes and interfaces that enable programs to manipulate characters and strings. Contains classes that enable programs to perform several tasks concurrently, or at the same time. Contains classes that enable programstodisplay basic graphics, such as displaying shapes and arcs. Fig NET Framework Class Library namespaces (a subset). (Part 2 of 2.)

55 7.12 Framework Class Library Namespaces (Cont.) 55 Good Programming Practice 7.2 The Visual Studio.NET documentation is easy to search and provides many details about each class. As you learn a class in this book, you should read about the class in the online documentation.

56 7.13 Passing Arguments: Pass-by-Value vs. Pass-by-Reference 56 Arguments are passed pass-by-value or pass-by-reference. When an argument is passed by value, the program makes a copy of the argument s value and passes the copy. Changes to the copy do not affect the original variable. When an argument is passed by reference, the original data can be accessed and modified directly.

57 Outline 57 Figure 7.11 demonstrates passing arguments by value and by reference. ByRefTest.vb 1 ' Fig. 7.11: ByRefTest.vb 2 ' Demonstrates passing by value and by reference. 3 Module ByRefTest 4 Sub Main() 5 Dim number1 As Integer = Console.WriteLine("Passing a value-type argument by value:") 8 Console.WriteLine("Before calling SquareByValue, " & _ 9 "number1 is {0}", number1) 10 SquareByValue(number1) ' passes number1 by value 11 Console.WriteLine("After returning from SquareByValue, " & _ 12 "number1 is {0}" & vbnewline, number1) 13 (1 of 4 ) Fig ByVal and ByRef used to pass value-type arguments. (Part 1 of 4.) 2009 Pearson Education, Inc. All rights reserved.

58 Outline Dim number2 As Integer = Console.WriteLine("Passing a value-type argument" & _ 17 " by reference:") 18 Console.WriteLine("Before calling SquareByReference, " & _ 19 "number2 is {0}", number2) 20 SquareByReference(number2) ' passes number2 by reference 21 Console.WriteLine("After returning from " & _ 22 "SquareByReference, number2 is {0}" & vbnewline, number2) Dim number3 As Integer = Console.WriteLine("Passing a value-type argument" & _ 27 " by reference, but in parentheses:") 28 Console.WriteLine("Before calling SquareByReference " & _ 29 "using parentheses, number3 is {0}", number3) 30 SquareByReference((number3)) ' passes number3 by value 31 Console.WriteLine( WriteLine("After returning from " & _ 32 "SquareByReference, number3 is {0}", number3) 33 End Sub ' Main ByRefTest.vb (2 of 4 ) Squaring number2 by reference. Squaring number1 by value. The inner set of parentheses evaluates number3 to its value and passes this value. Fig ByVal and ByRef used dto pass value-type arguments. (Part t2 of f4) 4.) 2009 Pearson Education, Inc. All rights reserved.

59 Outline 59 ByRefTest.vb ' squares number by value (note ByVal keyword) 36 Sub SquareByValue(ByVal number As Integer) 37 Console.WriteLine("After entering SquareByValue, " & _ 38 "number is {0}", number) 39 number *= number 40 Console.WriteLine( WriteLine("Before exiting SquareByValue, " & _ 41 "number is {0}", number) 42 End Sub ' SquareByValue ' squares number by reference (note ByRef keyword) 45 Sub SquareByReference(ByRef number As Integer) 46 Console.WriteLine("After entering SquareByReference" & _ 47 ", number is {0}", number) 48 number *= number 49 Console.WriteLine("Before exiting SquareByReference" & _ 50 ", number is {0}", number) 51 End Sub ' SquareByReference 52 End Module ' ByRefTest (3 of 4 ) ByVal indicates that its argument is passed by value. Squaring the number parameter value. ByRef receives its parameter by reference. Squaring the number parameter s reference. Fig ByVal and ByRef used dto pass value-type arguments. (Part t3 of f4) 4.) 2009 Pearson Education, Inc. All rights reserved.

60 Outline 60 ByRefTest.vb Passing a value-type argument by value: Before calling SquareByValue, number1 is 2 After entering SquareByValue, number is 2 Before exiting SquareByValue, number is 4 After returning from SquareByValue, number1 is 2 (4 of 4) Passing a value-type argument by reference: Before calling SquareByReference, number2 is 2 After entering SquareByReference, number is 2 Before exiting SquareByReference, number is 4 After returning from SquareByReference, number2 is 4 Passing a value-type argument by reference, but in parentheses: Before calling SquareByReference using parentheses, number3 is 2 After entering SquareByReference, number is 2 Before exiting SquareByReference, number is 4 After returning from SquareByReference, number3 is 2 Fig ByVal and ByRef used to pass value-type arguments. (Part 4 of 4.) 2009 Pearson Education, Inc. All rights reserved.

61 Outline 61 Error-Prevention Tip 7.4 ByRefTest.vb (5 of 5 ) When passing arguments by value, changes to the called method s copy do not affect the original variable s value. This prevents possible side effects that could hinder the development of correct and reliable software systems. Always pass value-type arguments by value unless you explicitly intend for the called method to modify the caller s data Pearson Education, Inc. All rights reserved.

62 7.14 Scope of Declarations 62 A declaration s scope is the portion of the program that can refer to the declared entity by its name without qualification. The basic scopes are: Block scope from the point of the declaration to the end of the block Method scope from the point of the declaration to the end of that method Module scope the entire body of the class or module. Namespace scope accessible to all other elements in the same namespace

63 7.14 Scope of Declarations (cont.) 63 If a local variable has the same name as a field of the class, the field is hidden this is called shadowing. A variable s lifetime is the period during which the variable exists in memory. Variables normally exist as long as their container exists. Error-Prevention Tip 7.5 Use different names for fields and local variables to help prevent subtle logic errors that occur when a method is called and a local variable of the method shadows a field of the same name in the class.

64 Outline 64 1 ' Fig. 7.12: Scope.vb 2 ' Scope class demonstrates instance and local variable scopes. 3 Public Class Scope 4 ' instance variable that is accessible to all methods of this class 5 Private x As Integer = ' method Begin creates and initializes local variable x and 8 ' calls methods UseLocalVariable and UseInstanceVariable 9 Public Sub Begin() 10 ' method's local variable x shadows instance variable x 11 Dim x As Integer = Console.WriteLine( WriteLine("local x in method Begin is " & x) UseLocalVariable() ' UseLocalVariable has local x 16 UseInstanceVariable() ' uses class Scope's instance variable x 17 UseLocalVariable() ' UseLocalVariable reinitializes local x 18 UseInstanceVariable() ' Scope's instance variable x retains value Console.WriteLine(vbNewLine & "local x in method Begin is " & x) 21 End Sub ' Begin Scope.vb (1 of 2 ) This instance variable is shadowed by any local variable named x. Method Begin declares a local variable x Fig Scoping rules in a class. (Part 1 of 2.) 2009 Pearson Education, Inc. All rights reserved.

65 Outline ' create and initialize local variable x during each call 24 Sub UseLocalVariable() 25 Dim x As Integer = 25 ' initialized in each call Console.WriteLine(vbNewLine & _ 28 "local x on entering method UseLocalVariable is " & x) Scope.vb (2 of 2 ) Subroutine UseLocalVariable declares a local variable x 29 x += 1 ' modifies this method's local l variable x Modifying the local 30 Console.WriteLine("local variable x before exiting method " & _ variable x 31 "UseLocalVariable is " & x) 32 End Sub ' UseLocalVariable ' modify class Scope's instance variable x during each call 35 Sub UseInstanceVariable() 36 Console.WriteLine(vbNewLine & "instance variable" & _ 37 " x on entering method UseInstanceVariable is " & x) 38 x *= 10 ' modifies class Scope's instance variable x 39 Console.WriteLine("instance variable " & _ 40 "x before exiting method UseInstanceVariable is " & x) 41 End Sub ' UseInstanceVariable 42 End Class ' Scope UseInstanceVariable does not declare local variables, so x refers to the instance variable. Fig Scoping rules in a class. (Part 2 of 2.) 2009 Pearson Education, Inc. All rights reserved.

66 Outline 66 1 ' Fig. 7.13: ScopeTest.vb 2 ' Testing class Scope. 3 Module ScopeTest 4 Sub Main() 5 Dim testscope As New Scope() 6 testscope.begin() 7 End Sub ' Main 8 End Module ' ScopeTest ScopeTest.vb local x in method Begin is 5 local x on entering method UseLocalVariable is 25 local variable x before exiting method UseLocalVariable is 26 instance variable x on entering method UseInstanceVariable is 1 instance variable x before exiting method UseInstanceVariable is 10 local x on entering method UseLocalVariable is 25 local variable x before exiting method UseLocalVariable is 26 instance variable x on entering method UseInstanceVariable is 10 instance variable x before exiting method UseInstanceVariable is 100 local x in method Begin is 5 Fig Module to test class Scope Pearson Education, Inc. All rights reserved.

67 7.15 Case Study: Random Number Generation 67 The element of chance can be introduced through class Random. Dim randomobject As New Random() Dim randomnumber As Integer = randomobject.next() Next generates a positive Integer between zero and Int32.MaxValue. The values returned by Next are actually pseudo-random numbers. The default seed value is based on the current time.

68 7.15 Case Study: Random Number Generation (Cont.) 68 We can produce integers in the range 1 6 by passing an argument to method Next: value = 1 + randomobject.next(6) The number 6 is the scaling factor. We shift the range of numbers produced by adding 1. Simplify the process by passing two arguments to Next: value = randomobject.next(1, 7)

69 Outline Figure 7.14 demonstrates the use of class Random and method Next by simulating 20 rolls of a six-sided 1 ' Fig. 7.14: RandomInteger.vb 2 die. ' Random integers from 1 to 6 created by calling Random method Next 3 Module RandomInteger 4 Sub Main() 5 Dim randomobject As New Random() ' create Random object 6 Dim randomnumber As Integer 7 8 ' generate 20 random numbers between 1 and 6 9 For i = 1 To randomnumber = randomobject.next(1, 7) 11 Console.Write(randomNumber & " ") If i Mod 5 = 0 Then ' is i a multiple of 5? 14 Console.WriteLine() 15 End If 16 Next 17 End Sub ' Main 18 End Module ' RandomInteger RandomInteger.vb Random numbers are generated by an object of class Random. The values that are produced are in the range from 1 to 6, inclusive. 69 Fig Random integers from 1 to 6 created by calling Random method Next Pearson Education, Inc. All rights reserved.

70 Outline 70 RollDice.vb 1 ' Fig. 7.15: RollDice.vb 2 ' Rolling four dice. 3 Public Class RollDice 4 Dim randomobject As New Random() ' create Random object 5 6 ' display results of four rolls 7 Private Sub rollbutton_click(byval sender As System.Object, _ 8 ByVal e As System.EventArgs) Handles rollbutton.click 9 ' method randomly assigns a face to each die 10 DisplayDie(die1PictureBox) 11 DisplayDie(die2PictureBox) 12 DisplayDie(die3PictureBox) 13 DisplayDie(die4PictureBox) 14 End Sub ' rollbutton_click 15 (1 of 2 ) Initializing a Random object. Fig Demonstrating four die rolls with graphical output. (Part 1 of 2.) 2009 Pearson Education, Inc. All rights reserved.

71 Outline 71 RollDice.vb 16 ' get a random die image 17 Sub DisplayDie(ByVal y diepicturebox As PictureBox) 18 ' generate random integer in range 1 to 6 19 Dim face As Integer = randomobject.next(1, 7) ' retrieve specific die image from resources 22 Dim pictureresource = My.Resources.ResourceManager.GetObject( ResourceManager _ 23 String.Format("die{0}", face)) ' convert pictureresource to type Image and display in PictureBox 26 diepicturebox.image = CType(pictureResource, Image) 27 End Sub ' DisplayDie 28 End Class ' RollDice (2 of 2 ) The values that are produced are in the range from 1 to 6, inclusive. Retrieving the picture from My.Resources. CType performs conversion from Object to Image. a) b) Fig Demonstrating four die rolls with graphical output. (Part 2 of 2.) 2009 Pearson Education, Inc. All rights reserved.

72 7.15 Case Study: Random Number Generation (cont.) 72 The Button control can be simply dragged and dropped onto the Form from the Toolbox. Name the control rollbutton and set its Text to Roll. Double click the Button to create the Click event handler. Note that the event handler is a Sub procedure.

73 7.15 Case Study: Random Number Generation (cont.) 73 The event handler calls method DisplayDie once for each PictureBox. Calling DisplayDie causes dice to appear as if they are being rolled. The images are embedded with the project as resources.

74 7.15 Case Study: Random Number Generation (cont.) 74 Double click My Project in the Solution Explorer. Click the Resources tab, then click the down arrow next to the Add Resource button (Fig. 7.16) to select Add Existing File... Locate the resources you wish to add and click the Open button. Save your project.

75 7.15 Case Study: Random Number Generation (cont.) 75 Fig Images added as resources.

76 7.15 Case Study: Random Number Generation (cont.) 76 To access the project s resources, use the method My.Resources.ResourceManager. ResourceManager GetObject. You must convert this Object to type Image to assign it to the PictureBox s Image property; Visual Basic s s CType function converts its first argument to the type specified in its second argument.

77 Outline 77 RollTwelveDice.vb 1 ' Fig. 7.17: RollTwelveDice.vb 2 ' Rolling 12 dice with frequency chart. 3 Public Class RollTwelveDice 4 Dim randomobject As New Random() ' generate random number 5 Dim ones As Integer ' count of die face 1 6 Dim twos As Integer ' count of die face 2 7 Dim threes As Integer ' count of die face 3 8 Dim fours As Integer ' count of die face 4 9 Dim fives As Integer ' count of die face 5 10 Dim sixes As Integer ' count of die face ' display result of twelve rolls 13 Private Sub rollbutton_click(byval sender As System.Object, _ 14 ByVal e As System.EventArgs) Handles rollbutton.click ' assign random faces to 12 dice using DisplayDie 17 DisplayDie(die1PictureBox) 18 DisplayDie(die2PictureBox) 19 DisplayDie(die3PictureBox) 20 DisplayDie(die4PictureBox) (1 of 5 ) Initializing a Random object. Fig Random class used to simulate rolling 12 six-sided dice. (Part 1 of 5.) 2009 Pearson Education, Inc. All rights reserved.

78 Outline DisplayDie(die5PictureBox) 22 DisplayDie(die6PictureBox) 23 DisplayDie(die7PictureBox) 24 DisplayDie(die8PictureBox) 25 DisplayDie(die9PictureBox) 26 DisplayDie(die10PictureBox) 27 DisplayDie(die11PictureBox) 28 DisplayDie(die12PictureBox) Dim total As Integer = ones + twos + threes + fours + fives + sixes 31 Dim output As String ' display frequencies of faces 34 output = ("Face" & vbtab & "Frequency" & vbtab & "Percent") 35 output &= (vbnewline & "1" & vbtab & ones & _ 36 vbtab & vbtab & String.Format("{0:P2}", ones / total)) 37 output &= (vbnewline & "2" & vbtab & twos & vbtab & _ 38 vbtab & String.Format( Format("{0:P2}", twos / total)) 39 output &= (vbnewline & "3" & vbtab & threes & vbtab & _ 40 vbtab & String.Format("{0:P2}", threes / total)) RollTwelveDice.vb (2 of 5 ) Using String.Format to print percentages to two decimal places. Fig Random class used to simulate rolling 12 six-sided dice. (Part 2 of 5.) 2009 Pearson Education, Inc. All rights reserved.

79 Outline output &= (vbnewline & "4" & vbtab & fours & vbtab & _ 42 vbtab & String.Format("{0:P2}", fours / total)) 43 output &= (vbnewline & "5" & vbtab & fives & vbtab & _ 44 vbtab & String.Format( Format("{0:P2}", fives / total)) 45 output &= (vbnewline & "6" & vbtab & sixes & vbtab & _ 46 vbtab & String.Format("{0:P2}", sixes / total) & vbnewline) 47 displaytextbox.text = output 48 End Sub ' rollbutton_click ' display a single die image 51 Sub DisplayDie(ByVal diepicturebox As PictureBox) 52 Dim face As Integer = randomobject.next(1, 7) ' retrieve specific die image from resources 55 Dim pictureresource = My.Resources.ResourceManager.GetObject( _ 56 String.Format("die{0}", face)) ' convert pictureresource to image type and load into PictureBox 59 diepicturebox.image = CType(pictureResource, Image) 60 RollTwelveDice.vb (3 of 5 ) Using String.Format to print percentages to two decimal places. Retrieving the picture from My.Resources. CType performs conversion from Object to Image. Fig Random class used to simulate rolling 12 six-sided dice. (Part 3 of 5.) 2009 Pearson Education, Inc. All rights reserved.

80 Outline ' maintain count of die faces 62 Select Case face 63 Case 1 ' die face 1 64 ones += 1 65 Case 2 ' die face 2 66 twos += 1 67 Case 3 ' die face 3 68 threes += 1 69 Case 4 ' die face 4 70 fours += 1 71 Case 5 ' die face 5 72 fives += 1 73 Case 6 ' die face 6 74 sixes += 1 75 End Select 76 End Sub ' DisplayDie 77 End Class ' RollTwelveDice RollTwelveDice.vb (4 of 5 ) Fig Random class used to simulate rolling 12 six-sided dice. (Part 4 of 5.) 2009 Pearson Education, Inc. All rights reserved.

81 Outline 81 a) b) RollTwelveDice.vb (5 of 5 ) displaytextbox Fig Random class used to simulate rolling 12 six-sidedsided dice. (Part 5 of 5.) 2009 Pearson Education, Inc. All rights reserved.

82 7.15 Case Study: Random Number Generation (cont.) 82 The TextBox control can be used both for displaying and inputting data. The data in the TextBox can be accessed via the Text property. p This TextBox s name is displaytextbox and the font size has been set to 9. The Multiline property has been set tto True.

83 7.16 Case Study: A Game of Chance 83 One of the most popular games of chance is a dice game known as craps": A player rolls two dice. After the dice have come to rest, the sum of the spots on the two upward faces is calculated. If the sum is 7 or 11 on the first throw, the player wins. If the sum is 2, 3 or 12 on the first throw (called craps ), the player loses. If the sum is 4, 5, 6, 8, 9 or 10 on the first throw, that sum becomes the player s point. To win, players must continue rolling the dice until they make their point (i.e., roll their point value). The player loses by rolling a 7 before making the point.

84 Outline 84 The application in Fig simulates the game of craps. 1 ' Fig 7.18: CrapsGame.vb 2 ' Craps game using class Random. 3 Public Class CrapsGame 4 ' die-roll constants t 5 Enum DiceNames 6 SNAKE_EYES = 2 7 TREY = 3 8 LUCKY_SEVEN = 7 Declaring constants 9 CRAPS = 7 through an enumeration. 10 YO_LEVEN = BOX_CARS = End Enum Dim mypoint As Integer ' total point 15 Dim mydie1 As Integer ' die1 face 16 Dim mydie2 As Integer ' die2 face 17 Dim randomobject As New Random() ' generate random number 18 Fig Craps game using class Random. (Part 1 of 7.) CrapsGame.vb (1 of 7 ) 2009 Pearson Education, Inc. All rights reserved.

85 Outline ' begins new game and determines point 20 Private Sub playbutton_click(byval sender As System.Object, _ 21 ByVal e As System.EventArgs) Handles playbutton.click ' initialize variables for new game 24 mypoint = 0 25 pointgroupbox.text = "Point" 26 statuslabel.text = String.Empty ' remove point-die images 29 pointdie1picturebox.image = Nothing 30 pointdie2picturebox.image = Nothing Dim sum As Integer = RollDice() ' roll dice and calculate sum 33 CrapsGame.vb (2 of 7 ) String.Empty represents a string with no characters (""). Setting the Image to Nothing causes a PictureBox to appear blank 34 ' check die roll The Select Case 35 Select Case sum statement analyzes the 36 Case DiceNames.LUCKY_SEVEN, DiceNames.YO_LEVEN roll. 37 rollbutton.enabled = False ' disable Roll button 38 statuslabel.text = "You Win!!!" Fig Craps game using class Random. (Part 2 of 7.) 2009 Pearson Education, Inc. All rights reserved.

86 Outline Case DiceNames.SNAKE_EYES, DiceNames.TREY, DiceNames.BOX_CARS 40 rollbutton.enabled = False ' disable Roll button 41 statuslabel.text = "Sorry. You Lose." 42 Case Else 43 mypoint = sum 44 pointgroupbox.text = "Point is " & sum 45 statuslabel.text = "Roll Again!" 46 DisplayDie(pointDie1PictureBox, mydie1) 47 DisplayDie(pointDie2PictureBox, mydie2) 48 playbutton.enabled = False ' disable Play button 49 rollbutton.enabled = True ' enable Roll button 50 End Select 51 End Sub ' playbutton_click 52 CrapsGame.vb (3 of 7 ) Fig Craps game using class Random. (Part 3 of 7.) 2009 Pearson Education, Inc. All rights reserved.

87 Outline ' determines outcome of next roll 54 Private Sub rollbutton_click(byval sender As System.Object, _ 55 ByVal e As System.EventArgs) Handles rollbutton.click Dim sum As Integer = RollDice() ' roll dice and calculate sum ' check outcome of roll 60 If sum = mypoint Then ' win 61 statuslabel.text = "You Win!!!" 62 rollbutton.enabled = False ' disable Roll button 63 playbutton.enabled = True ' enable Play button 64 ElseIf sum = DiceNames.CRAPS Then ' lose 65 statuslabel.text = "Sorry. You Lose." 66 rollbutton.enabled = False ' disable Roll button 67 playbutton.enabled = True ' enable Play button 68 End If 69 End Sub ' rollbutton_click 70 CrapsGame.vb (4 of 7 ) Determining if a losing roll is made. Fig Craps game using class Random. (Part 4 of 7.) 2009 Pearson Education, Inc. All rights reserved.

88 Outline ' display die image 72 Sub DisplayDie(ByVal diepicturebox As PictureBox, _ 73 ByVal face As Integer) ' retrieve specific die image from resources 76 Dim pictureresource = My.Resources.ResourceManager.GetObject( _ 77 String.Format("die{0}", face)) ' convert pictureresource to image type and load into PictureBox 80 diepicturebox.image = CType(pictureResource, Image) 81 End Sub ' DisplayDie 82 CrapsGame.vb (5 of 7 ) Fig Craps game using class Random. (Part 5 of 7.) 2009 Pearson Education, Inc. All rights reserved.

89 Outline ' generate random die rolls 84 Function RollDice() As Integer 85 ' determine random integer 86 mydie1 = randomobject.next(1, 7) 87 mydie2 = randomobject.next(1, 7) ' display rolls 90 DisplayDie(die1PictureBox, mydie1) 91 DisplayDie(die2PictureBox, mydie2) Return mydie1 + mydie2 ' return sum 94 End Function ' RollDice 95 End Class ' CrapsGame pointgroupbox playbutton a) b) rollbutton CrapsGame.vb (6 of 7 ) Fig Craps game using class Random. (Part 6 of 7.) 2009 Pearson Education, Inc. All rights reserved.

90 Outline 90 CrapsGame.vb c) d) (7 of 7 ) Fig Craps game using class Random. (Part 7 of 7.) 2009 Pearson Education, Inc. All rights reserved.

91 7.16 Case Study: A Game of Chance (Cont.) String.Empty represents a string with no characters (""). Setting the Image to Nothing causes a PictureBox to appear blank. 91

92 7.16 Case Study: A Game of Chance (Cont.) The GroupBox control is a container used to group related controls. Within the GroupBox pointdicegroup, we add two PictureBoxes. To add controls to a GroupBox, drag and drop the controls onto it. We set tthe GroupBox s Text property to Point. 92

93 7.16 Case Study: A Game of Chance (Cont.) Enumerations enhance program readability by providing descriptive identifiers for constant numbers or Strings. In this application, we created an Enumeration for the various dice combinations. Buttons are enabled and disabled with the Enabled property. 93

94 Outline Method overloading allows you to create methods with the same name but different parameters. Overload.vb 94 (1 of 2 ) Figure 7.19 uses overloaded method Square to calculate the square of both an Integer and a Double. 1 ' Fig. 7.19: Overload.vb 2 ' Using overloaded methods. 3 Module Overload 4 Sub Main() ' call Square methods with Integer then with Double 5 Console.WriteLine("The square of Integer 7 is " & Square(7) & _ 6 vbnewline & "The square of Double 7.5 is " & Square(7.5)) 7 End Sub ' Main 8 9 ' method Square takes an Integer and returns an Integer 10 Function Square(ByVal value As Integer) As Integer 11 Return Convert.ToInt32(value ^ 2) 12 End Function ' Square 13 Fig Using overloaded methods. (Part 1 of 2.) 2009 Pearson Education, Inc. All rights reserved.

95 Outline 95 Overload.vb 14 ' method Square takes a Double and returns a Double 15 Function Square(ByVal value As Double) As Double 16 Return value ^ 2 17 End Function ' Square 18 End Module ' Overload (2 of 2 ) The square of Integer 7 is 49 The square of Double 7.5 is Fig Using overloaded methods. (Part 2 of 2.) Good Programming Practice 7.3 Overloading methods that perform closely l related tasks can make programs clearer Pearson Education, Inc. All rights reserved.

96 7.17 Method Overloading (Cont.) 96 Overload resolution determines which method to call. This process first finds methods that could be used. Visual Basic converts variables as necessary when they are passed as arguments. The compiler selects the closest match.

97 Outline 97 The program in Fig illustrates the syntax Overload2.vb error that is generated when two methods have (1 of 2 ) the same signature and different return types. 1 ' Fig. 7.20: Overload2.vb 2 ' Using overloaded methods with identical signatures and 3 ' different return types. 4 Module Overload2 5 Sub Main() ' call Square methods with Integer and Double 6 Console.WriteLine("The square of Integer 7 is " & Square(7) & _ 7 vbnewline & "The square of Double 7.5 is " & Square(7.5)) 8 End Sub ' Main 9 10 ' method takes a Double and returns an Integer 11 Function Square(ByVal value As Double) As Integer 12 Return Convert.ToInt32(value ^ 2) 13 End Function ' Square 14 Fig Syntax error generated from overloaded methods with identical parameter lists and different return types. (Part 1 of 2.) 2009 Pearson Education, Inc. All rights reserved.

98 Outline ' method takes a Double and returns a Double 16 Function Square(ByVal value As Double) As Double 17 Return value ^ 2 18 End Function ' Square 19 End Module ' Overload2 Overload2.vb (2 of 2 ) Fig Syntax error generated from overloaded methods with identical parameter lists and different return types. (Part 2 of 2.) Common Programming Error 7.9 Creating overloaded methods with identical parameter lists and different return types is a compilation error Pearson Education, Inc. All rights reserved.

99 7.18 Optional Parameters 99 Optional parameters specify a default value that is assigned to the parameter if that argument is not passed. Sub ExampleMethod(ByVal value1 As Boolean, _ Optional ByVal value2 As Integer = 0) Both of these calls to ExampleMethod are valid: ExampleMethod(True) ExampleMethod(False, 10)

100 7.18 Optional Parameters (Cont.) 100 Common Programming Error 7.10 Declaring a non-optional parameter to the right of an Optional parameter is a syntax error. Common Programming Error 7.11 Not specifying a default value for an Optional parameter is a syntax error.

101 Outline The example in Fig demonstrates the use of optional parameters ' Fig 7.21: Power.vb 2 ' Optional argument demonstration with method Power. 3 Public Class Power 4 ' reads input and displays result 5 Private Sub calculatebutton_click(byval sender As System.Object, _ 6 ByVal e As System.EventArgs) Handles calculatebutton.click 7 8 Dim value As Integer 9 10 ' call version of Power depending on power input 11 If Not String.IsNullOrEmpty(powerTextBox.Text) Then 12 value = Power(Convert.ToInt32(baseTextBox.Text), _ 13 Convert.ToInt32(powerTextBox.Text)) Text)) 14 Else 15 value = Power(Convert.ToInt32(baseTextBox.Text)) 16 powertextbox.text = Convert.ToString(2) 17 End If outputlabel.text = Convert.ToString(value) 20 End Sub ' calculatebutton_click Power.vb (1 of 3 ) Using values from both TextBoxes. Using the value of one TextBox and omitting the optional parameter. Fig Optional argument demonstration with method Power. (Part 1 of 3.) 2009 Pearson Education, Inc. All rights reserved.

102 Outline ' use iteration to calculate power 23 Function Power(ByVal base As Integer, _ 24 Optional ByVal exponent As Integer = 2) As Integer Dim total As Integer = 1 ' initialize total For i = 1 To exponent ' calculate power 29 total *= base 30 Next Return total ' return result 33 End Function ' Power 34 End Class ' Power Power.vb (2 of 3 ) Using values from both TextBoxes. basetextbox e powertextbox e o a) Fig Optional argument demonstration with method Power. (Part 2 of 3.) 2009 Pearson Education, Inc. All rights reserved.

103 Outline 103 Power.vb b) (3 of 3 ) Power not necessary, optional parameter c) calculatebutton Fig Optional argument demonstration with method Power. (Part 3 of 3.) 2009 Pearson Education, Inc. All rights reserved.

104 7.19 Recursion 104 A recursive method calls itself either directly or indirectly. Recursive problem-solving approaches have a number of elements in common: The method solves only the simplest case the base case. When presented with a more complicated problem, the method invokes a fresh copy of itself to work on a smaller problem. A sequence of returns travels back up the line until the original method call returns the final result.

105 7.19 Recursion (Cont.) 105 Determining a Factorial Value Recursively The factorial of a nonnegative integer n, written n! (and read n factorial ), is the product n. ( n 1 ). ( n 2 ).. 1 We arrive at a recursive definition of the factorial method by observing the following relationship: n! = n. ( n 1 )!

106 7.19 Recursion (Cont.) 106 A recursive evaluation of 5! would proceed as in Fig Fig Recursive evaluation of 5!.

107 Figure 7.23 recursively calculates and prints factorials. Outline If number is less than or equal to 1, Factorial returns 1 and the method returns. If number is greater than 1, the answer is expressed as 1 ' Fig. 7.23: FactorialCalculator.vb 2 ' Calculating factorials using recursion. 3 Public Class FactorialCalculator 4 ' calculate factorial Factorial Calculator.vb (1 of 2 ) the product of number and a recursive call to Factorial. 5 Private Sub calculatebutton_click(byval sender As System.Object, _ 6 ByVal e As System.EventArgs) Handles calculatebutton.click 7 8 ' convert text in TextBox to Integer 9 Dim value As Integer = Convert.ToInt32(inputTextBox.Text) 10 displaytextbox.clear() ' reset TextBox ' call Factorial to perform calculation 13 For i = 0 To value 14 displaytextbox.text &= i & "! = " & Factorial(i) & vbnewline 15 Next 16 End Sub ' calculatebutton_click Fig Recursive factorial program. (Part 1 of 2.) 2009 Pearson Education, Inc. All rights reserved.

108 Outline ' recursively generates factorial of number 19 Function Factorial(ByVal number As Long) As Long 20 If number <= 1 Then ' base case 21 Return 1 22 Else 23 Return number * Factorial(number - 1) 24 End If 25 End Function ' Factorial 26 End Class ' FactorialCalculator Factorial Calculator.vb (2 of 2 ) Determining if the factorial has been resolved to its simplest form. Factorial makes recursive calls. Fig Recursive factorial program. (Part t2 of f2) 2.) 2009 Pearson Education, Inc. All rights reserved.

109 7.19 Recursion (Cont.) 109 Set the output TextBox s ScrollBars property to Vertical to display more outputs. Type Long is designed to store integer values in a range much larger than that of type Integer (such as factorials greater than 12!). The TextBox s s Clear method clears the text. Common Programming Error 7.12 Forgetting to return a value from a recursive method can result in logic errors.

110 7.19 Recursion (Cont.) 110 Common Programming Error 7.13 Omitting the base case or writing the recursion step so that it does not converge on the base case will cause infinite recursion, eventually exhausting memory. This is analogous to the problem of an infinite loop in an iterative (nonrecursive) solution.

111 7.20 (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System 111 An operation is a service that objects of a class provide to clients of the class. We can derive many of the operations of the classes in our ATM system by examining the verbs and verb phrases in the requirements document (Fig. 7.24).

112 7.20 (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System (Cont.) 112 Class ATM Verbs and verb phrases executes financial transactions BalanceInquiry [none in the requirements document] Withdrawal Deposit BankDatabase Account Screen Keypad [none in the requirements document] [none in the requirements document] authenticates a user, retrieves an account balance, credits an account by a deposit amount, debits an account by a withdrawal amount retrieves an account balance, credits an account by a deposit amount, debits an account by a withdrawal amount displays a message to the user receives numeric input from the user CashDispenser dispenses cash, indicates whether it contains enough cash to satisfy a withdrawal request DepositSlot receives a deposit envelope Fig Verbs and verb phrases for each class in the ATM system.

113 7.20 (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System (Cont.) 113 The UML represents operations (which h are implemented as methods) as follows: operationname( parameter1, parameter2,, parametern ) : returntype Each parameter consists of a parameter name and type: parametername : parametertype

114 7.20 (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System (Cont.) 114 Fig Classes in the ATM system with attributes and operations.

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved. 1 6 Functions and an Introduction to Recursion 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare

More information

Methods: A Deeper Look

Methods: A Deeper Look 1 2 7 Methods: A Deeper Look OBJECTIVES In this chapter you will learn: How static methods and variables are associated with an entire class rather than specific instances of the class. How to use random-number

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.5: Methods A Deeper Look Xianrong (Shawn) Zheng Spring 2017 1 Outline static Methods, static Variables, and Class Math Methods with Multiple

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly

More information

C Functions Pearson Education, Inc. All rights reserved.

C Functions Pearson Education, Inc. All rights reserved. 1 5 C Functions 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare Call me Ishmael. Herman Melville

More information

CSE123. Program Design and Modular Programming Functions 1-1

CSE123. Program Design and Modular Programming Functions 1-1 CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Function Definitions - Function Prototypes - Data

More information

Functions. Systems Programming Concepts

Functions. Systems Programming Concepts Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value

More information

Statements: Part Pearson Education, Inc. All rights reserved.

Statements: Part Pearson Education, Inc. All rights reserved. 1 6 Control Statements: Part 2 2 Who can control his fate? William Shakespeare, Othello The used key is always bright. Benjamin Franklin Not everything that can be counted counts, and not every thing that

More information

Function Call Stack and Activation Records

Function Call Stack and Activation Records 71 Function Call Stack and Activation Records To understand how C performs function calls, we first need to consider a data structure (i.e., collection of related data items) known as a stack. Students

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) Methods (Deitel chapter 6) 1 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) 1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number Generation

More information

Object Oriented Methods : Deeper Look Lecture Three

Object Oriented Methods : Deeper Look Lecture Three University of Babylon Collage of Computer Assistant Lecturer : Wadhah R. Baiee Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces,

More information

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++ Chapter 3 - Functions 1 Chapter 3 - Functions 2 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3. Functions 3.5 Function Definitions 3.6 Function Prototypes 3. Header Files 3.8

More information

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. Functions Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 5.1 Introduction 5.3 Math Library Functions 5.4 Functions 5.5

More information

Methods: A Deeper Look Pearson Education, Inc. All rights reserved.

Methods: A Deeper Look Pearson Education, Inc. All rights reserved. 1 6 Methods: A Deeper Look 2 The greatest invention of the nineteenth century was the invention of the method of invention. Alfred North Whitehead Call me Ishmael. Herman Melville When you call me that,

More information

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved. Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create

More information

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

6-1 (Function). (Function) !*+!#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x (Function) -1.1 Math Library Function!"#! $%&!'(#) preprocessor directive #include !*+!"#!, Function Description Example sqrt(x) square root of x sqrt(900.0) is 30.0 sqrt(9.0) is 3.0 exp(x) log(x)

More information

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved. C++ How to Program, 9/e 1992-2014 by Pearson Education, Inc. Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces, or components.

More information

Methods: A Deeper Look

Methods: A Deeper Look www.thestudycampus.com Methods: A Deeper Look 6.1 Introduction 6.2 Program Modules in Java 6.3 static Methods, static Fields and ClassMath 6.4 Declaring Methods with Multiple Parameters 6.5 Notes on Declaring

More information

ECET 264 C Programming Language with Applications

ECET 264 C Programming Language with Applications ECET 264 C Programming Language with Applications Lecture 10 C Standard Library Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 10

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times } Rolling a Six-Sided Die face = 1 + randomnumbers.nextint( 6 ); The argument 6 called the scaling factor represents the number of unique values that nextint should produce (0 5) This is called scaling

More information

6.5 Function Prototypes and Argument Coercion

6.5 Function Prototypes and Argument Coercion 6.5 Function Prototypes and Argument Coercion 32 Function prototype Also called a function declaration Indicates to the compiler: Name of the function Type of data returned by the function Parameters the

More information

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4 BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions

More information

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1 Chapter 6 Function C++, How to Program Deitel & Deitel Spring 2016 CISC1600 Yanjun Li 1 Function A function is a collection of statements that performs a specific task - a single, well-defined task. Divide

More information

www.thestudycampus.com Methods Let s imagine an automobile factory. When an automobile is manufactured, it is not made from basic raw materials; it is put together from previously manufactured parts. Some

More information

C++ Programming Lecture 11 Functions Part I

C++ Programming Lecture 11 Functions Part I C++ Programming Lecture 11 Functions Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Introduction Till now we have learned the basic concepts of C++. All the programs

More information

Control Statements: Part Pearson Education, Inc. All rights reserved.

Control Statements: Part Pearson Education, Inc. All rights reserved. 1 5 Control Statements: Part 2 2 Not everything that can be counted counts, and not every thing that counts can be counted. Albert Einstein Who can control his fate? William Shakespeare The used key is

More information

CT 229 Java Syntax Continued

CT 229 Java Syntax Continued CT 229 Java Syntax Continued 06/10/2006 CT229 Lab Assignments Due Date for current lab assignment : Oct 8 th Before submission make sure that the name of each.java file matches the name given in the assignment

More information

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura CS 2060 Week 4 1 Modularizing Programs Modularizing programs in C Writing custom functions Header files 2 Function Call Stack The function call stack Stack frames 3 Pass-by-value Pass-by-value and pass-by-reference

More information

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals INTERNET PROTOCOLS AND CLIENT-SERVER PROGRAMMING Client SWE344 request Internet response Fall Semester 2008-2009 (081) Server Module 2.1: C# Programming Essentials (Part 1) Dr. El-Sayed El-Alfy Computer

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 9 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines

More information

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Outline 12.1 Test-Driving the Craps Game Application 12.2 Random Number Generation 12.3 Using an enum in the Craps

More information

Unit 4. Lesson 4.1. Managing Data. Data types. Introduction. Data type. Visual Basic 2008 Data types

Unit 4. Lesson 4.1. Managing Data. Data types. Introduction. Data type. Visual Basic 2008 Data types Managing Data Unit 4 Managing Data Introduction Lesson 4.1 Data types We come across many types of information and data in our daily life. For example, we need to handle data such as name, address, money,

More information

Methods CSC 121 Fall 2016 Howard Rosenthal

Methods CSC 121 Fall 2016 Howard Rosenthal Methods CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

More information

Language Fundamentals

Language Fundamentals Language Fundamentals VBA Concepts Sept. 2013 CEE 3804 Faculty Language Fundamentals 1. Statements 2. Data Types 3. Variables and Constants 4. Functions 5. Subroutines Data Types 1. Numeric Integer Long

More information

Bit (0, 1) Byte (8 bits: 0-255) Numeral systems. Binary (bin) 0,1 Decimal (dec) 0, 1, 2, 3, Hexadecimal (hex) 0, 1, 2, 3, 1/13/2011

Bit (0, 1) Byte (8 bits: 0-255) Numeral systems. Binary (bin) 0,1 Decimal (dec) 0, 1, 2, 3, Hexadecimal (hex) 0, 1, 2, 3, 1/13/2011 * VB.NET Syntax I 1. Elements of code 2. Declaration and statements 3. Naming convention 4. Types and user defined types 5. Enumerations and variables Bit (0, 1) Byte (8 bits: 0-255) Numeral systems Binary

More information

Methods CSC 121 Fall 2014 Howard Rosenthal

Methods CSC 121 Fall 2014 Howard Rosenthal Methods CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class Learn the syntax of method construction Learn both void methods and methods that

More information

Agenda & Reading. VB.NET Programming. Data Types. COMPSCI 280 S1 Applications Programming. Programming Fundamentals

Agenda & Reading. VB.NET Programming. Data Types. COMPSCI 280 S1 Applications Programming. Programming Fundamentals Agenda & Reading COMPSCI 80 S Applications Programming Programming Fundamentals Data s Agenda: Data s Value s Reference s Constants Literals Enumerations Conversions Implicitly Explicitly Boxing and unboxing

More information

Methods CSC 121 Spring 2017 Howard Rosenthal

Methods CSC 121 Spring 2017 Howard Rosenthal Methods CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

More information

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module

More information

Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2016

Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2016 Introduction to 2 VISUAL BASIC 2016 edition Copyright HKTA Tang Hin Memorial Secondary School 2016 Table of Contents. Chapter....... 1.... More..... on.. Operators........................................

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments Basics Objectives Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments 2 Class Keyword class used to define new type specify

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Methods 2003 Prentice Hall, Inc. All rights reserved. 2 Introduction Modules Small pieces of a problem e.g., divide and conquer Facilitate design, implementation, operation and maintenance

More information

Programming Language 2 (PL2)

Programming Language 2 (PL2) Programming Language 2 (PL2) 337.1.1 - Explain rules for constructing various variable types of language 337.1.2 Identify the use of arithmetical and logical operators 337.1.3 Explain the rules of language

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Darshan Institute of Engineering & Technology for Diploma Studies

Darshan Institute of Engineering & Technology for Diploma Studies Overview of Microsoft.Net Framework: The Dot Net or.net is a technology that is an outcome of Microsoft s new strategy to develop window based robust applications and rich web applications and to keep

More information

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals VARIABLES WHAT IS A VARIABLE? A variable is a storage location in the computer s memory, used for holding information while the program is running. The information that is stored in a variable may change,

More information

Chapters are PDF documents posted online at the book s Companion Website (located at

Chapters are PDF documents posted online at the book s Companion Website (located at vbhtp6printonlytoc.fm Page ix Wednesday, February 27, 2013 11:59 AM Chapters 16 31 are PDF documents posted online at the book s Companion Website (located at www.pearsonhighered.com/deitel/). Preface

More information

Microsoft Visual Basic 2015: Reloaded

Microsoft Visual Basic 2015: Reloaded Microsoft Visual Basic 2015: Reloaded Sixth Edition Chapter Three Memory Locations and Calculations Objectives After studying this chapter, you should be able to: Declare variables and named constants

More information

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class. 1. What is C#? C# (pronounced "C sharp") is a simple, modern, object oriented, and type safe programming language. It will immediately be familiar to C and C++ programmers. C# combines the high productivity

More information

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions C++ PROGRAMMING SKILLS Part 3 User-Defined Functions Introduction Function Definition Void function Global Vs Local variables Random Number Generator Recursion Function Overloading Sample Code 1 Functions

More information

Microsoft Visual Basic 2005: Reloaded

Microsoft Visual Basic 2005: Reloaded Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations Objectives After studying this chapter, you should be able to: Declare variables and named

More information

VB FUNCTIONS AND OPERATORS

VB FUNCTIONS AND OPERATORS VB FUNCTIONS AND OPERATORS In der to compute inputs from users and generate results, we need to use various mathematical operats. In Visual Basic, other than the addition (+) and subtraction (-), the symbols

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

Chapter 2: Using Data

Chapter 2: Using Data Chapter 2: Using Data Declaring Variables Constant Cannot be changed after a program is compiled Variable A named location in computer memory that can hold different values at different points in time

More information

CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 7&8: Methods Lecture Contents What is a method? Static methods Declaring and using methods Parameters Scope of declaration Overloading

More information

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types Introduction to Computer Programming in Python Dr William C Bulko Data Types 2017 What is a data type? A data type is the kind of value represented by a constant or stored by a variable So far, you have

More information

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU CSE101-lec#12 Designing Structured Programs Introduction to Functions Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Designing structured programs in C: Counter-controlled repetition

More information

Introduction to C# Applications Pearson Education, Inc. All rights reserved.

Introduction to C# Applications Pearson Education, Inc. All rights reserved. 1 3 Introduction to C# Applications 2 What s in a name? That which we call a rose by any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Progra m Components in C++ 3.3 Ma th Libra ry Func tions 3.4 Func tions 3.5 Func tion De finitions 3.6 Func tion Prototypes 3.7 He a de r File s 3.8

More information

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved. 1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

Computer Programming C++ Classes and Objects 6 th Lecture

Computer Programming C++ Classes and Objects 6 th Lecture Computer Programming C++ Classes and Objects 6 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved Outline

More information

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5. Week 2: Console I/O and Operators Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.1) CS 1428 Fall 2014 Jill Seaman 1 2.14 Arithmetic Operators An operator is a symbol that tells the computer to perform specific

More information

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a, The (Outsource: Supplement) The includes a number of constants and methods you can use to perform common mathematical functions. A commonly used constant found in the Math class is Math.PI which is defined

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

More information

3.1. Chapter 3: The cin Object. Expressions and Interactivity

3.1. Chapter 3: The cin Object. Expressions and Interactivity Chapter 3: Expressions and Interactivity 3.1 The cin Object Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-1 The cin Object Standard input stream object, normally the keyboard,

More information

Chapters and Appendix F are PDF documents posted online at the book s Companion Website (located at

Chapters and Appendix F are PDF documents posted online at the book s Companion Website (located at Contents Chapters 16 27 and Appendix F are PDF documents posted online at the book s Companion Website (located at www.pearsonhighered.com/deitel/). Preface Before You Begin xix xxix 1 Introduction to

More information

Lecture 14. Daily Puzzle. Math in C. Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =?

Lecture 14. Daily Puzzle. Math in C. Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =? Lecture 14 Math in C Daily Puzzle Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =? Daily Puzzle SOLUTION Eleven plus two = twelve plus one Announcements

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

Lecture 7: Classes and Objects CS2301

Lecture 7: Classes and Objects CS2301 Lecture 7: Classes and Objects NADA ALZAHRANI CS2301 1 What is OOP? Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

Chapter 6 - Methods Prentice Hall. All rights reserved.

Chapter 6 - Methods Prentice Hall. All rights reserved. Chapter 6 - Methods 1 Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math Class Methods 6.4 Methods 6.5 Method Definitions 6.6 Argument Promotion 6.7 Java API Packages 6.8 Random-Number Generation

More information

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long LESSON 5 ARITHMETIC DATA PROCESSING The arithmetic data types are the fundamental data types of the C language. They are called "arithmetic" because operations such as addition and multiplication can be

More information

Chapter 2. Outline. Simple C++ Programs

Chapter 2. Outline. Simple C++ Programs Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6.

More information

.Net Technologies. Components of.net Framework

.Net Technologies. Components of.net Framework .Net Technologies Components of.net Framework There are many articles are available in the web on this topic; I just want to add one more article over the web by explaining Components of.net Framework.

More information

Flag Quiz Application

Flag Quiz Application T U T O R I A L 17 Objectives In this tutorial, you will learn to: Create and initialize arrays. Store information in an array. Refer to individual elements of an array. Sort arrays. Use ComboBoxes to

More information

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1 OBJECT ORIENTED SIMULATION LANGUAGE OOSimL Reference Manual - Part 1 Technical Report TR-CSIS-OOPsimL-1 José M. Garrido Department of Computer Science Updated November 2014 College of Computing and Software

More information

1001ICT Introduction To Programming Lecture Notes

1001ICT Introduction To Programming Lecture Notes 1001ICT Introduction To Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 1, 2015 1 M Environment console M.1 Purpose This environment supports programming

More information

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous Assignment 3 Methods Review CSC 123 Fall 2018 Notes: All homework must be submitted via e-mail. All parts of assignment must be submitted in a single e-mail with multiple attachments when required. Notes:

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction 1. Which language is not a true object-oriented programming language? A. VB 6 B. VB.NET C. JAVA D. C++ 2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a)

More information

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming. Programming Fundamentals for Engineers - 0702113 7. Functions Muntaser Abulafi Yacoub Sabatin Omar Qaraeen 1 Modular programming Your program main() function Calls AnotherFunction1() Returns the results

More information

Chapter 2. Building Multitier Programs with Classes The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Chapter 2. Building Multitier Programs with Classes The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill Chapter 2 Building Multitier Programs with Classes McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. Objectives Discuss object-oriented terminology Create your own class and instantiate

More information

C++ Overview. Chapter 1. Chapter 2

C++ Overview. Chapter 1. Chapter 2 C++ Overview Chapter 1 Note: All commands you type (including the Myro commands listed elsewhere) are essentially C++ commands. Later, in this section we will list those commands that are a part of the

More information

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial CSI31 Lecture 5 Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial 1 3.1 Numberic Data Types When computers were first developed, they were seen primarily as

More information

Module 4: Data Types and Variables

Module 4: Data Types and Variables Module 4: Data Types and Variables Table of Contents Module Overview 4-1 Lesson 1: Introduction to Data Types 4-2 Lesson 2: Defining and Using Variables 4-10 Lab:Variables and Constants 4-26 Lesson 3:

More information

DigiPen Institute of Technology

DigiPen Institute of Technology DigiPen Institute of Technology Presents Session Two: Overview of C# Programming DigiPen Institute of Technology 5001 150th Ave NE, Redmond, WA 98052 Phone: (425) 558-0299 www.digipen.edu 2005 DigiPen

More information

ANSI C Programming Simple Programs

ANSI C Programming Simple Programs ANSI C Programming Simple Programs /* This program computes the distance between two points */ #include #include #include main() { /* Declare and initialize variables */ double

More information

Introduction to Microsoft.NET

Introduction to Microsoft.NET Introduction to Microsoft.NET.NET initiative Introduced by Microsoft (June 2000) Vision for embracing the Internet in software development Independence from specific language or platform Applications developed

More information