1 / 65

Methods

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

vonda
Télécharger la présentation

Methods

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Methods

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

  3. 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

  4. You have already seen methods used In a couple of different places • As event handlers in GUI programs • As members of a class

  5. In this set of slides we will explore the use of methods as a way of breaking a problem into smaller pieces where each piece is easier to solve.

  6. At this point you have learned to write quite complex programs, that contain decisions and loops. … but most of your programs are still quite small and easy to manage. What if I gave you an assignment to write a 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 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 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 we call this functional decomposition -- breaking the program down into more manageable blocks (pieces). We often write a program as a series of pieces or blocks

  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 to play a dice game.

  12. Let’s do a top-down design. Tell the user what we are going to do Declare some variables Roll the dice Display the results See if user wants to play again

  13. Let’s do a top-down design. Tell the user what we are going to do Declare some variables You could write all of this code in a big long Main( ) routine. Roll the dice Display the results See if user wants to play again

  14. Let’s do a top-down design. Tell the user what we are going to do Declare some variables Or … you can break the problem up into smaller pieces, and write a method to do each piece. Roll the dice Display the results See if user wants to play again

  15. Let’s do a top-down design. Tell the user what we are going to do boxcars Display “boxcars” Declare some variables snake eyes Display “snake-eyes” Roll the dice Display the results Display value of dice See if user wants to play again

  16. Let’s do a top-down design. Tell the user what we are going to do ask … do you want to play again (y or n)? Declare some variables Get the user’s Input. Save it in “again” Roll the dice Display the results not y or n Display “invalid input” See if user wants to play again

  17. Writing these as methods boxcars Display “boxcars” A method will have one well defined thing that it does. snake eyes Display “snake-eyes” We will have the ability to give a method any data that it needs to do its job. Display value of dice If appropriate, a methodcan return the results of its work.

  18. Method Syntax These are parameters. Each parameter has a data type and a name. The type of data returned by this method. The method’s name intWiggleYourEars( intparameter1, intparameter2) { // statements } method header The body of the method is made up of valid C# statements (providing a service), enclosed in curly braces. method block (body)

  19. Just as a reminder … Main( ) is a method which satisfies all the conditions specified earlier. Header static void Main() Block { (body) }

  20. 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 .Netlibrary, accessed via using statements.

  21. Methods that return a value As an example of a method that returns a value, consider the Sqrtmethod 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 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.

  22. 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

  23. 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.

  24. 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:

  25. 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)

  26. 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); Generate values up to, but not including 4 (1-3) Start at 1

  27. 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

  28. 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.

  29. Writing a Method What job will the method do? What data does it need to do it’s work? What will the method return?

  30. Here is the activity diagram for the method we need to write to display the output of a roll. boxcars Display “boxcars” snake eyes Display “snake-eyes” What is it’s job (service provided)? What data does it need? What should it return? Display value of dice

  31. 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

  32. The Method Prologue // The DisplayResultsmethod // Purpose: show the results of rolling the dice // Parameters: two integer values, the dice // Returns: nothing

  33. This method does not return a value. boxcars Display “boxcars” snake eyes void DisplayResults(int d1, int d2) { } Display “snake-eyes” Display value of dice This method takes two parameters, the value of the dice that were thrown.

  34. boxcars Display “boxcars” static void DisplayResults(int d1, int d2) { Console.Write("You rolled "); if (d1 == BOX && d2 == BOX) Console.WriteLine("Box Cars"); else if (d1 == SNAKE && d2 == SNAKE) Console.WriteLine("Snake Eyes"); else Console.WriteLine("{0} and {1}", d1, d2); } snake eyes Display “snake-eyes” Display value of dice

  35. ask … do you want to play again (y or n)? Here is the activity diagram for the method we need to see if the user wants to roll again. Get the user’s Input. Save it In “again” What is it’s job (service it provides)? What data does it need? What should it return? not y or n Display “invalid input”

  36. The Method Prologue // The GoAgain method // Purpose: get and validate the user’s input // Parameters: none // Returns: the computer choice as a boolean // true – go again // false - quit

  37. static boolGoAgain() { const char YES = 'y'; const char NO = 'n'; char yn = YES; do { Console.Write("Do you want to roll again (y or n)? "); yn = char.Parse(Console.ReadLine()); yn = char.ToLower(yn); if (yn != YES && yn != NO) Console.WriteLine("Invalid input."); } while (yn != YES && yn != NO); if (yn == YES) return true; else return false; } } ask … do you want to play again (y or n)? Get the user’s Input. Save it In “again” not y or n Display “invalid input”

  38. Now with these methods, our Main( ) method just looks like this: static void Main(string[] args) { int die1, die2; Random dice = new Random( ); do { die1 = dice.Next(1, BOX+1); die2 = dice.Next(1, BOX + 1); DisplayResults(die1, die2); } while (GoAgain( ) ); Console.WriteLine("Thanks for playing ... goodbye"); Console.ReadLine( ); } // end of Main We could combine these into a single method, but we like a method to do one thing.

  39. Scope Scope has to do with where a variable can be seen. global variables (class level variables) local variables (method level variables)

  40. A related term is storage class or lifetime, which defines how long a variable exists within a program. automaticvariables – come into existence when they are declared, and exist until the block in which they are declared is left.. staticvariables – exist for the lifetime of the program Class level variables – exist for the lifetime of the program (const’s at the class level)

  41. global variables must be declared outside of any method. They need to be declared within a class as static. Constants are automatically static. Example using System; class Program { static string globalValue = "I was declared outside any method"; 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 the name localValue is used twice. In this case the scope of localValue is inside of Main( ). It is a localvariable. 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.

  42. 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.

  43. 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.

  44. The PseudoCode Programming Process From “Code Complete” by Steve McConnell

  45. 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!

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

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

  48. Step Four: Think about how you will test your method once it is written. Write down some test cases (input and output)

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

More Related