Upload
vonda
View
75
Download
0
Tags:
Embed Size (px)
DESCRIPTION
Methods. Topics. Top Down Design. Built-in methods. Methods that return a value. Void methods. Programmer defined methods. Scope. Objectives. At the end of this topic, students should be able to:. Break a problem into smaller pieces. Write programs that use built-in methods - PowerPoint PPT Presentation
Citation preview
Methods
Topics
Built-in methodsMethods that return a valueVoid methodsProgrammer defined methodsScope
Top Down Design
ObjectivesAt 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
You have already seen methods used as Event Handlers in GUI programs.
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.
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?
A big Problemthat’s hard to
solve
A smaller problemthat is easier to solve
A smaller problemthat is easier to solve
A smaller problemthat is easier to solve
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
You have already written quite a few methods.
In the Graphical User Interface programs thatyou have written, the event handlers you havewritten are methods.
As an example, consider a programthat you might write that works with a
speed detection radar system.
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.
The speed of the car, v, can be calculated using the formula
v = (6.685 X 108)(f1 – f0)/(f1 + f0)
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
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.
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.
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.
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.
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)
Just as a reminder … Main( ) is a method which satisfies all theconditions specified earlier.
Header static void Main( )Block {(body)
}
Built-in MethodsIn 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.
Methods that return a valueAs 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.
The Math classThe 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
Random Number GeneratorThe .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.
Random Number GeneratorA 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:
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)
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)
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
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.
Writing a Method
What job will the method do?What data does it need to do it’s work?What will the method return?
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?
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
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
static double GetDouble(string prompt){
}
This methodreturns adouble.
This method takes one parameter.This is the string we will use toprompt the user.
// 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; }
Now consider the method thatdisplays the output.
What is it’s job (service it provides)?What data does it need?What should it return?
The Method Prologue
// The outPutDouble method // Purpose: Outputs a double with 2 digits after the decimal // Parameters: then value to output // Returns: none
// 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}");}
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?
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
// 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; }
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()
ScopeScope has to do with where a variable can be seen.
global variables (class level variables)
local variables (method level variables)
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)
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.
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.
Static VariablesA 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.
The PseudoCode Programming ProcessFrom “Code Complete” by Steve McConnell
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!
Step Two: Clearly state the problem that themethod will solve. - What does it do - What are its inputs - What are its outputs
Step Three: Write a method prologue - The method name - Purpose - Parameters - Return value
Step Four: Think about how you will testyour method once it is written. Write downsome test cases (input and output)
Step Five: Research available code libraries and algorithms … has someone else written thecode that you need?
Step Six: Write the Pseudocode for yourmethod.
Step Seven: Walk through your pseudocodeand see if it makes sense. Does it work? If not --revisit your design.
Step Eight: Write down the method declaration(the first line of the method)
Step Nine: Add your pseudocode to your programas comments.
Step Ten: Fill in the actual code beloweach set of comments (pseudocode)
Step Eleven: Walk through your code,mentally check for errors.
Step Twelve: Compile your code – fixsyntax errors.
Step Thirteen: Use your test cases to see ifyour method works correctly.
PracticeWrite the prologue for a method named CalcRatiothat takes two integer parameters and returns a double.
PracticeWrite the code for this method. The ratiois found by dividing the first parameter by the second.
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
PracticeWrite 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
Some Sample Exchange Rates
$1.00 = 0.679459 Euros
$1.00 = 13.3134 Mexican Pesos
$1.00 = 1.04338 Canadian Dollars
Assume that we have used FunctionalDecomposition to break this problem upinto pieces, and have determined thatwe need a method that does the actualcurrency conversion.
Use the Pseudocode Programming Processto develop the code for this method.