Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods...

69
Methods

Transcript of Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods...

Page 1: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Methods

Page 2: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Topics

Built-in methodsMethods that return a value

Void methods

Programmer defined methods

Scope

Top Down Design

Page 3: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Objectives

At the end of this topic, students should be able to:

Write programs that use built-in methodsKnow how to use methods in the Math libraryCorrectly write and use methods in a programDescribe what scope is and how it affects the executionof a program.Effectively use the pseudo-code programming process

Break a problem into smaller pieces

Page 4: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

You have already seen methods used as Event Handlers in GUI programs.

Page 5: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Methods allow us to break a program intosmall pieces where each piece is easier to solve

than the program as a whole.

Methods also provide us with a way of using thesame code over and over again in the same program,

or even re-using the code in a different program.Method parameters allow us to us methods with

different sets of data each time the method is called.

Page 6: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

So far the programs you have written have beenquite small, and not overly complex.

But what if I gave you an assignment to write a complex console program that would contain 50,000 lines of code?

Page 7: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

A big Problemthat’s hard to

solve

Page 8: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

A smaller problemthat is easier to solve

A smaller problemthat is easier to solve

A smaller problemthat is easier to solve

Page 9: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

We often write a program as a series of pieces or blocks

We do this because it is easier to understand what goes on in a small block (piece) of code,

because we can re-use the same block (piece) of codemany times from within our program, and

we call this functional decomposition -- breaking the program down into more manageable blocks (pieces).

in C# these smaller blocks (pieces) are called methods

because it allows a team of programmers to work ondifferent part of a program in parallel

Page 10: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

You have already written quite a few methods.

In the Graphical User Interface programs thatyou have written, the event handlers you havewritten are methods.

Page 11: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

As an example, consider a programthat you might write that works with a

speed detection radar system.

Page 12: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

A radar gun emits a beam of microwaves at some frequency f0. The beam bounces off an

approaching car and is reflected back to the radar gun. The frequency of the returned beam is

shifted slightly from f0 to f1 due to the motion of the car.

Page 13: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

The speed of the car, v, can be calculated using the formula

v = (6.685 X 108)(f1 – f0)/(f1 + f0)

Page 14: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Let’s do a top-down design.

Tell the user what we are going to do

Declare some variables

Get the transmittedfrequency

Calculate the speed

Get the receivedfrequency

Display the results

Page 15: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Let’s do a top-down design.

Tell the user what we are going to do

Declare some variables

Get the transmittedfrequency

Calculate the speed

Get the receivedfrequency

Display the results

You could write all of this codein a big long Main( ) routine.

Page 16: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Let’s do a top-down design.

Tell the user what we are going to do

Declare some variables

Get the transmittedfrequency

Calculate the speed

Get the receivedfrequency

Display the results

Or … you can break the problemup into smaller pieces, and writea method to do each piece.

Page 17: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Let’s do a top-down design.

Tell the user what we are going to do

Declare some variables

Get the transmittedfrequency

Calculate the speed

Get the receivedfrequency

Display the results

We can write aSimple methodfor each step.

Page 18: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Writing the methods

A method will have one well defined thing that it does.

We will have the ability to givea method any data that itneeds to do its job.

If appropriate, a method can return the results of its work.

Page 19: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Method Syntax

int WiggleYourEars( int parameter1, int parameter2){

// statements

}

The type of datareturned by thismethod.

The method’sname

These are parameters.Each parameter has a data type and a name.

The body of the methodis made up of valid C#statements that provide a service, enclosed in curly braces.

method header

method block (body)

Page 20: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Just as a reminder … Main( ) is a method which satisfies all theconditions specified earlier.

Header static void Main( )Block {(body)

}

Page 21: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Built-in Methods

In general, if you can find some written and tested code that does what you want, it is better to use that already existing code than to re-create the code yourself.

saves timefewer errorstested under all conditions

Most programming languages, including C#, includelibraries of pre-written and tested methods that docommon programming tasks. In C#, these librariesare in the .Net library, accessed via using statements.

Page 22: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Methods that return a value

As an example of a method that returns a value, considerthe Sqrt method in the Math class.

To find the square root of the number 9, we wouldwrite

result = Math.Sqrt (9);

this is the method’s argument.

The argument may be a literal value,a variable, a constant, or an expression.

Some methods may take more than oneargument. If so, they are separated bycommas (a comma delimited list).

the value returned by the functionis called its return value.

A method can only have onereturn value.

this is called a method invocation.It can be used anywhere an expressioncan be used. The Sqrt method belongsto the Math class.

Page 23: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

The Math class

The Sqrt method is found in the Math class.

Other common functions in the Math class:

Pow (int x, int y) calculates xy double

Abs (double n) absolute value of n double

Ceil (double n ) smallest integer >= n double

Floor (double n) largest integer <= n double

name function (service) return type

Page 24: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Random Number Generator

The .Net library provides a class that we can use to createa random number generator. To create a random numbergenerator object, we write

Random randoms = new Random( );

This is the referenceto the Random object. This creates the Random object in the Heap.

This initializes the Random object.

Page 25: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Random Number Generator

A random number generator generates a pseudo-random integer value between zero and 2,147,483,646.

To get a random number, we call the Next( ) method that is declared as part of the Random class. The Next method looks like this:

Page 26: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Random Number Generator

To get a random number within a specific range we scalethe result …. for example, to get a number between 0 and 2,inclusive

int n = randoms.Next( 3 );

generates value up to, but not including 3 (0-2)

Page 27: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Random Number Generator

To shift the range of the random numbers, for example, to geta random number between 1 and 3, use this form of the Nextmethod:

int n = randoms.Next(1, 4);

Start at 1 Generate values up to, but not including 4 (1-3)

Page 28: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Random Number Generator

To get a repeatable sequence of pseudo-random numbers,use the same seed when creating the Random object

Random randoms = new Random( 3 );

*

* same machine, same compiler

Page 29: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Methods that don’t return a value

methods that don’t return a value are called void methods.

void methods are written as statements. They cannot be usedin an expression, as expressions must return a typed value.

void methods can have zero or more parameters.

Page 30: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Writing a Method

What job will the method do?What data does it need to do it’s work?What will the method return?

Page 31: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Consider the method we will useto prompt the user and get theuser’s input.

What is it’s job (service provided)?What data does it need?What should it return?

Page 32: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

The Method Prologue

Every method should have a method prologue.The method prologue tells us * What the purpose of the method is * What data the method needs to do its work * What data the method returns

Page 33: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

The Method Prologue

// The getDouble Method// Purpose: Prompt the user and get a double value // Parameters: The user prompt// Returns: the double value entered by the user

Page 34: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

static double GetDouble(string prompt){

}

This methodreturns adouble.

This method takes one parameter.This is the string we will use toprompt the user.

Page 35: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

// The getDouble Method// Purpose: Prompt the user and get a double value // Parameters: The user prompt// Returns: the double value entered by the user static double GetDouble(string prompt) { // declare a double to sore user input double value;

// prompt the user WriteLine(prompt);

// get the input and return it value = double.Parse(ReadLine()); return value; }

Page 36: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Now consider the method thatdisplays the output.

What is it’s job (service it provides)?What data does it need?What should it return?

Page 37: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

The Method Prologue

// The outPutDouble method // Purpose: Outputs a double with 2 digits after the decimal // Parameters: then value to output // Returns: none

Page 38: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

// The outPutDouble method// Purpose: Outputs a double with 2 digits after the decimal// Parameters: then value to output// Returns: none static void outputDouble(double value){ WriteLine($"{value:f2}");}

Page 39: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Now consider the method thatcalculates the speed of the car.

What is it’s job (service it provides)?What data does it need?What should it return?

Page 40: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

The Method Prologue

// The findSpeed Method // Purpose: Calculate the speed of an oncoming car // Parameters: The frequency of the sent signal and the // frequency of the received signal // Returns: the speed of the car

Page 41: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

// The findSpeed Method // Purpose: Calculate the speed of an oncoming car // Parameters: The frequency of the sent signal and // the frequency of the received signal // Returns: the speed of the car static double findSpeed(double f0, double f1) { // declarations const double SPEED_FACTOR = 6.685e8; double speed = 0;

// formula for calculating speed speed = SPEED_FACTOR * (f1 - f0) / (f1 + f0);

// return it return speed; }

Page 42: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Now with these methods, ourMain( ) method just looks like this:

static void Main() {

// Tell the user what the program does WriteLine("This program finds the speed of an oncoming car,"); WriteLine("given the frequency of the transmitted radar beam and"); WriteLine("the frequency of the received radar beam.");

// declare some variables double transmittedFreq, receivedFreq;

// prompt the user and get the transmitted frequency transmittedFreq = GetDouble("\nEnter transmitted frequency: “);

// prompt the user and get the received frequency receivedFreq = GetDouble("\nEnter received frequency: ");

// call the method to compute the speed double speedOfCar = findSpeed(transmittedFreq, receivedFreq);

// output the result Write("\nThe speed of the oncoming car in mph: "); outputDouble(speedOfCar);

Console.ReadLine(); }//End Main()

Page 43: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Scope

Scope has to do with where a variable can be seen.

global variables (class level variables)

local variables (method level variables)

Page 44: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

A related term is storage class or lifetime, which defines how longa variable exists within a program.

automatic variables – come into existence when theyare declared, and exist until the block in which they aredeclared is left..

static variables – exist for the lifetime of the program

Class level variables – exist for the lifetime of the program(const’s at the class level)

Page 45: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Exampleusing System;

class Program{ static string globalValue = "I was declared outside any method"; static void Main() { WriteLine("Entering main( ) ..."); string localValue = "I was declared in Main( )"; SomeMethod( ); WriteLine("Local value = {0}", localValue); ReadKey(true); }//End Main()

static void SomeMethod( ) { WriteLine("Entering SomeMethod( )..."); string localValue = "I was declared in SomeMethod( )"; WriteLine("Global value = {0}", globalValue); WriteLine("Local value = {0}", localValue); }//End SomeMethod()}//End class Program

global variables must be declared outsideof any method. They need to be declared withina class as static. Constants are automatically static.

the name localValueis used twice. In this casethe scope of localValueis inside of Main( ). It isa local variable.

localValue is also declaredin this method, but itsscope is just inside themethod. It cannot be seenoutside of the method. Itis a different variable than the one declared in Main( ).It is a local variable.

Page 46: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.
Page 47: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

BlocksAnytime we use curly braces to delineate a piece of code,that code is called a block. We can declare variables thatare local to a block and have block scope.

Local variables declared in a nested block are onlyknown to the block that they are declared in.

When we declare a variable as part of a loop, for examplefor (int j = 0; j< MAX; j++)…

the variable j will have the block of the loop as its scope.

Page 48: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Static Variables

A static variable comes into existence when it is declared and itlives until the program ends. A static variable has class scope –that is, it is visible to all of the methods in the class. Static variables live in the data segment.

Page 49: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

The PseudoCode Programming ProcessFrom “Code Complete” by Steve McConnell

Page 50: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Step One: Before doing any work on the method itself, make sure that the methodis really required, and that the job of themethod is well defined. Methods should doone thing!

Page 51: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Step Two: Clearly state the problem that themethod will solve. - What does it do - What are its inputs - What are its outputs

Page 52: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Step Three: Write a method prologue - The method name - Purpose - Parameters - Return value

Page 53: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Step Four: Think about how you will testyour method once it is written. Write downsome test cases (input and output)

Page 54: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Step Five: Research available code libraries and algorithms … has someone else written thecode that you need?

Page 55: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Step Six: Write the Pseudocode for yourmethod.

Page 56: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Step Seven: Walk through your pseudocodeand see if it makes sense. Does it work? If not --revisit your design.

Page 57: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Step Eight: Write down the method declaration(the first line of the method)

Page 58: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Step Nine: Add your pseudocode to your programas comments.

Page 59: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Step Ten: Fill in the actual code beloweach set of comments (pseudocode)

Page 60: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Step Eleven: Walk through your code,mentally check for errors.

Page 61: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Step Twelve: Compile your code – fixsyntax errors.

Page 62: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Step Thirteen: Use your test cases to see ifyour method works correctly.

Page 63: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Practice

Write the prologue for a method named CalcRatio

that takes two integer parameters and returns a double.

Page 64: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Practice

Write the code for this method. The ratio

is found by dividing the first parameter by the second.

Page 65: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Practice

Write a complete program that

(1) gets two input values from the user

(2) passes those values to the CalcRatio method

(3) displays the result

Page 66: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Practice

Write a program that converts dollar values into another currency. The program should work as follows:

(1) Prints an introduction to the program

(2) Gets a currency conversion factor and currency name from user

(3) Gets a dollar value

(4) Calculates and displays the value in the new currency

-- Write a method to do the currency calculation

Page 67: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Some Sample Exchange Rates

$1.00 = 0.679459 Euros

$1.00 = 13.3134 Mexican Pesos

$1.00 = 1.04338 Canadian Dollars

Page 68: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Assume that we have used FunctionalDecomposition to break this problem upinto pieces, and have determined thatwe need a method that does the actualcurrency conversion.

Page 69: Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.

Use the Pseudocode Programming Processto develop the code for this method.