Download presentation
Presentation is loading. Please wait.
Published byWilfred Lawrence Modified over 9 years ago
1
Methods
2
Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design
3
Objectives At the end of this topic, students should be able to: 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 Break a problem into smaller pieces
4
You have already seen methods used as Event Handlers in GUI programs.
5
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.
6
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?
7
A big Problem that’s hard to solve
8
A smaller problem that is easier to solve A smaller problem that is easier to solve A smaller problem that is easier to solve
9
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 code many 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 on different part of a program in parallel
10
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.
11
As an example, consider a program that you might write that works with a speed detection radar system.
12
A radar gun emits a beam of microwaves at some frequency f 0. 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 f 0 to f 1 due to the motion of the car.
13
The speed of the car, v, can be calculated using the formula v = (6.685 X 10 8 )(f 1 – f 0 )/(f 1 + f 0 )
14
Let’s do a top-down design. Tell the user what we are going to do Declare some variables Get the transmitted frequency Calculate the speed Get the received frequency Display the results
15
Let’s do a top-down design. Tell the user what we are going to do Declare some variables Get the transmitted frequency Calculate the speed Get the received frequency Display the results You could write all of this code in a big long Main( ) routine.
16
Let’s do a top-down design. Tell the user what we are going to do Declare some variables Get the transmitted frequency Calculate the speed Get the received frequency Display the results Or … you can break the problem up into smaller pieces, and write a method to do each piece.
17
Let’s do a top-down design. Tell the user what we are going to do Declare some variables Get the transmitted frequency Calculate the speed Get the received frequency Display the results We can write a Simple method for each step.
18
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.
19
Method Syntax int WiggleYourEars( int parameter1, int parameter2) { // statements } The type of data returned by this method. The method’s name These are parameters. Each parameter has a data type and a name. The body of the method is made up of valid C# statements that provide a service, enclosed in curly braces. method header method block (body)
20
Just as a reminder … Main( ) is a method which satisfies all the conditions specified earlier. Header static void Main( ) Block { (body) }
21
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.
22
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 the method’s argument. The argument may be a literal value, a variable, a constant, or an expression. Some methods may take more than one argument. If so, they are separated by commas (a comma delimited list). the value returned by the function is called its return value. A method can only have one return value. this is called a method invocation. It can be used anywhere an expression can be used. The Sqrt method belongs to the Math class.
23
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 x y double Abs (double n)absolute value of ndouble Ceil (double n )smallest integer >= ndouble Floor (double n)largest integer <= ndouble namefunction (service)return type
24
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 is the reference to the Random object. This creates the Random object in the Heap. This initializes the Random object.
25
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:
26
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)
27
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)
28
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
29
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.
30
Writing a Method What job will the method do? What data does it need to do it’s work? What will the method return?
31
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?
32
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
33
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
34
static double GetDouble(string prompt) { } This method returns a double. This method takes one parameter. This is the string we will use to prompt the user.
35
// 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; }
36
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?
37
The Method Prologue // The outPutDouble method // Purpose: Outputs a double with 2 digits after the decimal // Parameters: then value to output // Returns: none
38
// 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}"); }
39
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?
40
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
41
// 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; }
42
Now with these methods, our Main( ) 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()
43
Scope Scope has to do with where a variable can be seen. global variables (class level variables) local variables (method level variables)
44
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)
45
Example using 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 outside of any method. They need to be declared within a class as static. Constants are automatically static. 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.
47
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.
48
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.
49
The PseudoCode Programming Process From “Code Complete” by Steve McConnell
50
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!
51
Step Two: Clearly state the problem that the method will solve. - What does it do - What are its inputs - What are its outputs
52
Step Three: Write a method prologue - The method name - Purpose - Parameters - Return value
53
Step Four: Think about how you will test your method once it is written. Write down some test cases (input and output)
54
Step Five: Research available code libraries and algorithms … has someone else written the code that you need?
55
Step Six: Write the Pseudocode for your method.
56
Step Seven: Walk through your pseudocode and see if it makes sense. Does it work? If not -- revisit your design.
57
Step Eight: Write down the method declaration (the first line of the method)
58
Step Nine: Add your pseudocode to your program as comments.
59
Step Ten: Fill in the actual code below each set of comments (pseudocode)
60
Step Eleven: Walk through your code, mentally check for errors.
61
Step Twelve: Compile your code – fix syntax errors.
62
Step Thirteen: Use your test cases to see if your method works correctly.
63
Practice Write the prologue for a method named CalcRatio that takes two integer parameters and returns a double.
64
Practice Write the code for this method. The ratio is found by dividing the first parameter by the second.
65
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
66
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
67
Some Sample Exchange Rates $1.00 = 0.679459 Euros $1.00 = 13.3134 Mexican Pesos $1.00 = 1.04338 Canadian Dollars
68
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.
69
Use the Pseudocode Programming Process to develop the code for this method.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.