Method Overloading and Parameter Passing in CS112: An Introduction to Programming, Slides of C programming

An outline and code examples for lecture #13 of the cs112 introduction to programming course at yale university. The lecture covers method overloading and parameter passing in c#. Method overloading allows the use of the same method name for multiple methods that perform the same task on different data types. Parameter passing determines how the actual arguments in a method invocation are copied into the formal arguments in the method. Examples of method overloading, method signatures, and call-by-value and call-by-reference parameter passing.

Typology: Slides

2010/2011

Uploaded on 10/05/2011

christina
christina 🇺🇸

4.6

(23)

393 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CS 112 Introduction to
Programming
Lecture #13:
Method Overloading
and Parameter Passing
http://flint.cs.yale.edu/cs112/
2
Outline
rAdmin. and review
qMore about defining and using methods
¦Method header
¦Overloading and signature
¦Method parameter passing
¦Method body
¦Variable scope and duration
3
Recap: Methods
rA method should provide a well-defined, easy-to-
understand functionality
mA method takes input (parameters), performs some actions,
and (sometime) returns a value
rWriting a custom method
mHeader
Properties ReturnType Name( Param1, Param2, … )
mBody
Contains the code of what the method does
Contains the return value if necessary
mAll methods must be defined inside of a class
Outline
MaximumValue.cs
1// MaximumValue.cs
2// Finding the maximum of three doubles.
3
4using System;
5
6class MaximumValue
7 {
8// main entry point for application
9static void Main( string[] args )
10 {
11 // obtain user input and convert to double
12 Console.Write( "Enter first floating-point value: " );
13 double number1 = Double.Parse( Console.ReadLine() );
14
15 Console.Write( "Enter second floating-point value: " );
16 double number2 = Double.Parse( Console.ReadLine() );
17
18 Console.Write( "Enter third floating-point value: " );
19 double number3 = Double.Parse( Console.ReadLine() );
20
21 // call method Maximum to determine largest value
22 double max = Maximum( number1, number2, number3 );
23
24 // display maximum value
25 Console.WriteLine("\nmaximum is: " + max );
26
27 } // end method Main
The program gets three
values from the user
The three values are then passed
to the Maximum method for use
Outline
MaximumValue.cs
Program Output
28
29 // Maximum method uses method Math.Max to help determine
30 // the maximum value
31 static double Maximum( double x, double y, double z )
32 {
33 return Math.Max( x, Math.Max( y, z ) );
34
35 } // end method Maximum
36
37 } // end class MaximumValue
Enter first floating-point value: 37.3
Enter second floating-point value: 99.32
Enter third floating-point value: 27.1928
maximum is: 99.32
The Maximum method receives 3
variables and returns the largest one
The use of Math.Max uses the Max
method in class Math. The dot
operator is used to call it.
6
The Dual Roles of C# Classes
rProgram modules:
a list of (static) method declarations and (static) data
fields
To make a method static, a programmer applies the
static modifier to the method definition
The result of each invocation of a class method is
completely determined by the actual parameters (and
static fields of the class)
To use a static method:
ClassName.MethodName(…);
rBlueprints for generating objects:
Create an object
Call methods of the object:
objectName.MethodName(…);
pf3
pf4
pf5

Partial preview of the text

Download Method Overloading and Parameter Passing in CS112: An Introduction to Programming and more Slides C programming in PDF only on Docsity!

CS 112 Introduction to

Programming

Lecture #13:

Method Overloading

and Parameter Passing

http://flint.cs.yale.edu/cs112/

Outline

r Admin. and review

q More about defining and using methods

¶ Method header

¶ Overloading and signature

¶ Method parameter passing

¶ Method body

¶ Variable scope and duration

Recap: Methods

r A method should provide a well-defined, easy-to-

understand functionality

m A method takes input (parameters), performs some actions,

and (sometime) returns a value

r Writing a custom method

m Header

  • Properties ReturnType Name ( Param1 , Param2 , … )

m Body

  • Contains the code of what the method does
  • Contains the return value if necessary

m All methods must be defined inside of a class

Outline

MaximumValue.cs

1 // MaximumValue.cs 2 // Finding the maximum of three doubles. 3 4 using System; 5 6 class MaximumValue 7 { 8 // main entry point for application 9 static void Main( string[] args ) 10 { 11 // obtain user input and convert to double 12 Console.Write( "Enter first floating-point value: " ); 13 double number1 = Double.Parse( Console.ReadLine() ); 14 15 Console.Write( "Enter second floating-point value: " ); 16 double number2 = Double.Parse( Console.ReadLine() ); 17 18 Console.Write( "Enter third floating-point value: " ); 19 double number3 = Double.Parse( Console.ReadLine() ); 20 21 // call method Maximum to determine largest value 22 double max = Maximum( number1, number2, number3 ); 23 24 // display maximum value 25 Console.WriteLine("\nmaximum is: " + max ); 26 27 } // end method Main

The program gets three

values from the user

The three values are then passed

to the Maximum method for use

Outline

MaximumValue.cs

Program Output

29 // Maximum method uses method Math.Max to help determine 30 // the maximum value 31 static double Maximum( double x, double y, double z ) 32 { 33 return Math.Max( x, Math.Max( y, z ) ); 34 35 } // end method Maximum 36 37 } // end class MaximumValue

Enter first floating-point value: 37. Enter second floating-point value: 99. Enter third floating-point value: 27.

maximum is: 99.

The Maximum method receives 3

variables and returns the largest one

The use of Math.Max uses the Max

method in class Math. The dot

operator is used to call it.

The Dual Roles of C# Classes

r Program modules:

• a list of (static) method declarations and (static) data

fields

• To make a method static, a programmer applies the

static modifier to the method definition

• The result of each invocation of a class method is

completely determined by the actual parameters (and

static fields of the class)

• To use a static method:

ClassName.MethodName(…);

r Blueprints for generating objects:

• Create an object

• Call methods of the object:

objectName.MethodName(…);

Explicitly Creating Objects

r A class name can be used as a type to

declare an object reference variable

String title;

Random myRandom;

r An object reference variable holds the

address of an object

r No object has been created with the above

declaration

r The object itself must be created using the

new keyword

Creating and Accessing Objects

r We use the new operator to create an object

Random myRandom;

myRandom = new Random();

This calls theThis calls the RandomRandom constructorconstructor , which is, which is

a special method that sets up the objecta special method that sets up the object

r Creating an object is called instantiation

m An object is an instance of a particular class

r To call an ( instance ) method on an object, we

use the variable (not the class), e.g.,

Random generator1 = new Random();

int num = generate1.Next();

Example: the Random class

Random Random ()

Some methods from the Random class

int Next ()

// returns an integer from 0 to Int32.MaxValue

int Next (int max)

// returns an integer from 0 upto but not including max

int Next (int min, int max)

// returns an integer from min upto but not including max

double NextDouble ( )

// returns a double number from 0 to 1

See RandomNumbers.cs

Outline

RandomInt.cs

1 // RandomInt.cs 2 // Random integers. 3 4 using System; 5 using System.Windows.Forms; 6 7 // calculates and displays 20 random integers 8 class RandomInt 9 { 10 // main entry point for application 11 static void Main( string[] args ) 12 { 13 int value; 14 string output = ""; 15 16 Random randomInteger = new Random(); 17 18 // loop 20 times 19 for ( int i = 1; i <= 20; i++ ) 20 { 21 // pick random integer between 1 and 6 22 value = randomInteger.Next( 1, 7 ); 23 output += value + " "; // append value to output 24 25 // if counter divisible by 5, append newline 26 if ( i % 5 == 0 ) 27 output += "\n"; 28 29 } // end for structure 30

Creates a new Random object

Will set value to a random number

from1 up to but not including 7

Format the output to only have

5 numbers per line

Outline

RandomInt.cs

Program Output

31 MessageBox.Show( output, "20 Random Numbers from 1 to 6", 32 MessageBoxButtons.OK, MessageBoxIcon.Information ); 33 34 } // end Main 35 36 } // end class RandomInt

Display the output in a message box

A Quick Summary

r If a method is a static method

m Call the method by

ClassName.MethodName(…);

r If a method of a class is not a static method,

then it is an instance method

m Create an object using the new operator

m Call methods of the object:

objectVariableName.MethodName(…);

r We will study instance methods in more detail

in the future

Recall: Calling a Method

r Each time a method is called, the actual arguments in

the invocation are copied into the formal arguments

static int SquareSum (int num1, int num2)

int sum = num1 + num2;

return sum * sum;

int num = SquareSum (2, 3);

Parameters: Modifying Formal Arguments

r You can use the formal arguments (parameters) as

variables inside the method

r Question: If a formal argument is modified inside a

method, will the actual argument be changed?

static int Square ( int x )

x = x * x;

return x;

static void Main ( string[] args )

int x = 8;

int y = Square( x );

Console.WriteLine ( x );

Parameter Passing

r If a modification on the formal argument has no

effect on the actual argument,

m it is call by value

r If a modification on the formal argument can

change the actual argument,

m it is call by reference

Call-By-Value and Call-By-Reference in C#

r Depend on the type of the formal argument

r For the simple data types, it is call-by-value

r Change to call-by-reference

m The ref keyword and the out keyword change a

parameter to call-by-reference

• If a formal argument is modified in a method, the value is

changed

• The ref or out keyword is required in both method

declaration and method call

• ref requires that the parameter be initialized before

enter a method while out requires that the parameter be

set before return from a method

Example: ref

static void Foo( int p ) {++p;}

static void Main ( string[] args )

int x = 8;

Foo( x ); // a copy of x is made

Console.WriteLine( x );

static void Foo( ref int p ) {++p;}

static void Main ( string[] args )

int x = 8;

Foo( ref x ); // x is ref

Console.WriteLine( x );

} See TestRef.cs

Example: out

static void Split( int timeLate,

out int days,

out int hours,

out minutes )

days = timeLate / 10000;

hours = (timeLate / 100) % 100;

minutes = timeLate % 100;

static void Main ( string[] args )

int d, h, m;

Split( 12345, out d, out h, out m );

Console.WriteLine( “{0}d {1}h {2}m”, d, h, m );

See TestOut.cs

Outline

RefOutTest.cs

1 // RefOutTest.cs 2 // Demonstrating ref and out parameters. 3 4 using System; 5 using System.Windows.Forms; 6 7 class RefOutTest 8 { 9 // x is passed as a ref int (original value will change) 10 static void SquareRef( ref int x ) 11 { 12 x = x * x; 13 } 14 15 // original value can be changed and initialized 16 static void SquareOut( out int x ) 17 { 18 x = 6; 19 x = x * x; 20 } 21 22 // x is passed by value (original value not changed) 23 static void Square( int x ) 24 { 25 x = x * x; 26 } 27 28 static void Main( string[] args ) 29 { 30 // create a new integer value, set it to 5 31 int y = 5; 32 int z; // declare z, but do not initialize it 33

When passing a value by reference

the value will be altered in the rest

of the program as well

Since x is passed as out the variable

can then be initialed in the method

Since not specified, this value is defaulted to being

passed by value. The value of x will not be changed

elsewhere in the program because a duplicate of the

variable is created.

Since the methods are void

they do not need a return value.

Outline

RefOutTest.cs

34 // display original values of y and z 35 string output1 = "The value of y begins as " 36 + y + ", z begins uninitialized.\n\n\n"; 37 38 // values of y and z are passed by value 39 RefOutTest.SquareRef( ref y ); 40 RefOutTest.SquareOut( out z ); 41 42 // display values of y and z after modified by methods 43 // SquareRef and SquareOut 44 string output2 = "After calling SquareRef with y as an " + 45 "argument and SquareOut with z as an argument,\n" + 46 "the values of y and z are:\n\n" + 47 "y: " + y + "\nz: " + z + "\n\n\n"; 48 49 // values of y and z are passed by value 50 RefOutTest.Square( y ); 51 RefOutTest.Square( z ); 52 53 // values of y and z will be same as before because Square 54 // did not modify variables directly 55 string output3 = "After calling Square on both x and y, " + 56 "the values of y and z are:\n\n" + 57 "y: " + y + "\nz: " + z + "\n\n"; 58 59 MessageBox.Show( output1 + output2 + output3, 60 "Using ref and out Parameters", MessageBoxButtons.OK, 61 MessageBoxIcon.Information ); 62 63 } // end method Main 64 65 } // end class RefOutTest

The calling of the SquareRef

and SquareOut methods

The calling of the

SquareRef and SquareOut

methods by passing the

variables by value

Outline

RefOutTest.cs

Program Output