Functions - Utah Valley University

Download Report

Transcript Functions - Utah Valley University

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
Know how to use methods in the Math library
Correctly write and use methods in a program
Describe what scope is and how it affects the execution
of a program.
Effectively use the pseudo-code programming process
You have already seen methods used
as Event Handlers in GUI programs.
Methods allow us to break a program into
small pieces where each piece is easier to solve
than the program as a whole.
Methods also provide us with a way of using the
same 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 been
quite 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 Problem
that’s hard to
solve
A smaller problem
that is easier to solve
A smaller problem
that is easier to solve
A smaller problem
that is easier to solve
We often write a program as a series of pieces or blocks
we call this functional decomposition
-- breaking the program down into more
manageable blocks (pieces).
in C# these smaller blocks (pieces) are called methods
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 code
many times from within our program, and
because it allows a team of programmers to work on
different part of a program in parallel
You have already written quite a few methods.
In the Graphical User Interface programs that
you have written, the event handlers you have
written are methods.
As an example, consider a program
that 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 transmitted
frequency
Get the received
frequency
Calculate the speed
Display the results
Let’s do a top-down design.
Tell the user what
we are going to do
Declare some
variables
Get the transmitted
frequency
Get the received
frequency
Calculate the speed
Display the results
You could write all of this code
in 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 transmitted
frequency
Get the received
frequency
Calculate the speed
Display the results
Or … you can break the problem
up into smaller pieces, and write
a 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 transmitted
frequency
Get the received
frequency
Calculate the speed
Display the results
We can write a
Simple method
for each step.
Writing the methods
A method will have one well
defined thing that it does.
We will have the ability to give
a method any data that it
needs to do its job.
If appropriate, a method can
return the results of its work.
Method Syntax
The type of data
returned by this
method.
method header
The method’s
name
These are parameters.
Each parameter has a
data type and a name.
int WiggleYourEars( int parameter1, int parameter2)
{
// statements
method block (body)
}
The body of the method
is made up of valid C#
statements that provide a service,
enclosed in curly braces.
Just as a reminder … Main( ) is a method which satisfies all the
conditions specified earlier.
Header
Block
(body)
static void Main( )
{
}
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 time
fewer errors
tested under all conditions
Most programming languages, including C#, include
libraries of pre-written and tested methods that do
common programming tasks. In C#, these libraries
are in the .Net library, accessed via using statements.
Methods that return a value
As an example of a method that returns a value, consider
the Sqrt method in the Math class.
To find the square root of the number 9, we would
write
result = Math.Sqrt (9);
this is called a method invocation.
It can be used anywhere an expression
can be used. The Sqrt method belongs
to the Math class.
this is the method’s argument.
the value returned by the function
is called its return value.
The argument may be a literal value,
a variable, a constant, or an expression.
A method can only have one
return value.
Some methods may take more than one
argument. If so, they are separated by
commas (a comma delimited list).
The Math class
The Sqrt method is found in the Math class.
Other common functions in the Math class:
name
function (service)
return type
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
Random Number Generator
The .Net library provides a class that we can use to create
a random number generator. To create a random number
generator object, we write
Random randoms = new Random( );
This initializes the Random object.
This is the reference
to the Random object.
This creates the Random object in the Heap.
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:
Random Number Generator
To get a random number within a specific range we scale
the 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 get
a random number between 1 and 3, use this form of the Next
method:
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 used
in 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 use
to prompt the user and get the
user’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
This method
returns a
double.
static double GetDouble(string prompt)
{
}
This method takes one parameter.
This is the string we will use to
prompt 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
Console.WriteLine(prompt);
}
// get the input and return it
value = double.Parse(Console.ReadLine());
return value;
Now consider the method that
displays 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)
{
Console.WriteLine("{0:f2}", value);
}
Now consider the method that
calculates 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, our
Main( ) method just looks like this:
static void Main()
{
// Tell the user what the program does
Console.WriteLine("This program finds the speed of an oncoming car,");
Console.WriteLine("given the frequency of the transmitted radar beam and");
Console.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
Console.Write("\nThe speed of the oncoming car in mph: ");
outputDouble(speedOfCar);
Console.ReadLine();
}//End Main()
Scope
Scope 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 long
a variable exists within a program.
automatic variables – come into existence when they
are declared, and exist until the block in which they are
declared 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)
Example
global variables must be declared outside
of any method. They need to be declared within
a class as static. Constants are automatically static.
using System;
class Program
{
static string globalValue = "I was declared outside any method";
the name localValue
is used twice. In this case
the scope of localValue
is inside of Main( ). It is
a local variable.
localValue is also declared
in this method, but its
scope is just inside the
method. It cannot be seen
outside of the method. It
is a different variable than
the one declared in Main( ).
It is a local variable.
static void Main()
{
Console.WriteLine("Entering main( ) ...");
string localValue = "I was declared in Main( )";
SomeMethod( );
Console.WriteLine("Local value = {0}", localValue);
Console.ReadLine( );
}//End Main()
static void SomeMethod( )
{
Console.WriteLine("Entering SomeMethod( )...");
string localValue = "I was declared in SomeMethod( )";
Console.WriteLine("Global value = {0}", globalValue);
Console.WriteLine("Local value = {0}", localValue);
}//End SomeMethod()
}//End class Program
Blocks
Anytime we use curly braces to delineate a piece of code,
that code is called a block. We can declare variables that
are local to a block and have block scope.
Local variables declared in a nested block are only
known to the block that they are declared in.
When we declare a variable as part of a loop, for example
for (int j = 0; j< MAX; j++)
…
the variable j will have the block of the loop as its scope.
Static Variables
A static variable comes into existence when it is declared and it
lives 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 Process
From “Code Complete” by Steve McConnell
Step One: Before doing any work on the
method itself, make sure that the method
is really required, and that the job of the
method is well defined. Methods should do
one thing!
Step Two: Clearly state the problem that the
method 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 test
your method once it is written. Write down
some test cases (input and output)
Step Five: Research available code libraries
and algorithms … has someone else written the
code that you need?
Step Six: Write the Pseudocode for your
method.
Step Seven: Walk through your pseudocode
and 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 program
as comments.
Step Ten: Fill in the actual code below
each set of comments (pseudocode)
Step Eleven: Walk through your code,
mentally check for errors.
Step Twelve: Compile your code – fix
syntax errors.
Step Thirteen: Use your test cases to see if
your method works correctly.
Practice
Write the prologue for a method named CalcRatio
that takes two integer parameters and returns a double.
Practice
Write the code for this method. The ratio
is 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
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
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 Functional
Decomposition to break this problem up
into pieces, and have determined that
we need a method that does the actual
currency conversion.
Use the Pseudocode Programming Process
to develop the code for this method.