1 / 36

Lec.4 Methods: Functional Abstraction

Lec.4 Methods: Functional Abstraction. Jiang (Jen) ZHENG May 18 th , 2005. Outline. Quick Review About Lab2 Implementation Detail Remote Access Submission Method Concepts Method invocation Static method Call by value Scope of variables Method Recursion.

esharpe
Download Presentation

Lec.4 Methods: Functional Abstraction

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. Lec.4Methods: Functional Abstraction Jiang (Jen) ZHENG May 18th, 2005

  2. Outline • Quick Review • About Lab2 • Implementation Detail • Remote Access • Submission • Method Concepts • Method invocation • Static method • Call by value • Scope of variables • Method Recursion CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  3. Quick Review: Statements and Block • Variable declaration statementsEx: double size=1.5, x; • Expression statements • Assignment expression Ex: area= width*height; • Method call expression Ex: System.out.println(…); • Empty Statement: ; (no action) • Conditional Statement: if-else, switch • Iterative Statement: for, while • Other statements:break, continue • Block: a grouping of a number of statements enclosed by braces. Can be nested blocks. CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  4. Operator Associativity ( ) ++(postfix) --(postfix) Left to right +(unary) -(unary) ++(prefix) --(prefix) ! Right to left new (type)expr Right to left * / % Left to right + - Left to right < <= > >= Left to right == != Left to right && Left to right || Left to right = += -= *= /= %= etc. Right to left Quick Review: Boolean Algebra • Relational and equality operators • <, >, ==, <=, >=, != • Logical Operators • &&, ||, ! • Operator Precedence and Associativity CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  5. About Lab2: Implementation Detail • How to use Package? • import tio.*; • Compile the java files of the tio package • The hierarchical of your program and the tio package • Fibonacci Numbers: • F(0) = 1, F(1) = 1, F(2) = F(1)+F(0) = 2, • F(3) = F(2) + F(1) = 2 + 1 = 3 • F(4) = F(3) + F(2) = 3 + 2 = 5 • F(5) = F(4) + F(3) = 5 + 3 = 8 • F(6) = F(5) + F(4) = 8 + 5 = 13 • F(7) = F(6) + F(5) = 13 + 8 = 21 … • Implementation: • use two parameters to represent the previous two F values of the current number • Update the two F values as the current number is going forward • Special situation: • F(0) = F(1) =1 CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  6. About Remote Access Your Pitt Account • Using telnet from your dos window. • telnet unixs.cis.pitt.edu • Using F-Secure SSH Client software (Recommend) • Or compile and run from your home PC • Demo the first two CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  7. Submission • You should be able to submit your assignment now. • The submission directory is: /afs/cs.pitt.edu/public/incoming/CS401/zheng/yourname/ • Submission Command: • cp [filename] [submission directory] • For example:cp Fibonacci.java /afs/cs.pitt.edu/public/incoming/CS401/zheng/SStachelski/lab2 CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  8. More About Switch statement • Evaluate the init_expr expression • Entering Point: • the caselabel having a constant value that matches the value of the expression found in step 1; • the defaultlabel if there is no match; • terminate switch if there is no default label, . • Continue executing statements in order • Exiting Point: • the end of switch • a break is encountered. • Demo ex4.java CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  9. Methods and Method Calls • If programs are short • We can write the code as one contiguous segment • The logic is probably simple • There are not too many variables • Not too likely to make a lot of errors • As programs get longer • Programming in a single segment gets more and more difficult • Logic is more complex • Many variables / expressions / control statements CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  10. Methods and Method Calls • Chances of “bugs” entering code is higher • Isolating and fixing is also harder • If multiple people are working on the program, it is difficult to “break up” if written as one segment • If parts need to be modified or added, it is difficult with one large segment • If similar actions are taken in various parts of the program, it is inefficient to code them all separately • And can also introduce errors • Most of these problems can be solved by breaking our program into smaller segments • Ex: Break some sticks! CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  11. Method Invocation • Method (or function or subprogram) • A segment of code that is logically separate from the rest of the program • When invoked (i.e. called) control jumps from main to the method and it executes • Usually with parameters (arguments) • When it is finished, control reverts to the next statement after the method call CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  12. Method Invocation • When a method is called or invoked • the program control passes to the method • the method does its work • the program control is passed back Program Control Program Control Method Call Program Control CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  13. Functional Abstraction • Methods provide us with functional (or procedural) abstraction • We do not need to know all of the implementation details of the methods in order to use them • We simply need to know • What arguments (parameters) we must provide • What the effect of the method is (i.e. what does it do?) • The actual implementation could be done in several different ways • Ex: Predefined method: sort(Object [] a) • There are many ways to sort! CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  14. Predefined Methods • There are MANY predefined methods in Java • Look in the online API • These are often called in the following way: ClassName.methodName(param_list) • Where ClassName is the class in which the method is defined • Where methodName is the name of the method • Where param_list is a list of 0 or more variables or expressions that are passed to the method Ex: Y = Math.sqrt(X); • These are called STATIC methods or CLASS methods • They are associated with a class, not with an object CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  15. Predefined Methods • Some are also called in the following way ClassName.ObjectName.methodName(param_list) • Where ObjectName is the name of a static, predefined object that contains the method Ex: System.out.println(“Hello There”); • System is a predefined class • out is a predefined PrintStream object within System • println is a method within PrintStream • We’ll use these now, but discuss their nature more when we discuss object-oriented program. • For now we will concentrate on static methods CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  16. Static Method In One Page • static method / class method / predefined method • General Form: • public static ReturnType Identifier (ParameterList) block • For Ex: public static double square ( double x) { double result; // Variable Declaration result = x*x; // statements return result; // return statement: can return a value or return a // value of an expression. Ex: return x*x; } • Return Type • the type of the value returned • Or void if nothing returned. • Parameter List • 0 or more parameters passed to the method • Each parameter: type identifier • Place holder for actual values. • public keyword is optional. Exception: main() CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  17. Return Value vs. Void • Java methods have two primary uses: • To act as a function, returning a result to the calling code • In Java these methods are declared with return types, and are called within an assignment or expression Ex: X = Console.in.readDouble(); Y = (Math.sqrt(X))/2; • To act as a subroutine or procedure, executing code but not explicitly returning a result • In Java these methods are declared to be void, and are called as separate stand-alone statements Ex: System.out.println(“Wacky”); Arrays.sort(myData); CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  18. Writing Static Methods • What if we need to use a method that is not predefined? • We will have to write it ourselves • Syntax: public static void methodName(param_list) { // method body } public static retval methodName(param_list) { // method body } • Where retval is some Java type • When method is not void, there MUST be a return statement CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  19. Writing Static Methods • So what about the param_list? • It is a way in which we pass values into our methods • This enables methods to process different information at different points in the program • Makes them more flexible • In the method definition: • List of type identifier pairs, separated by commas • Called formal parameters, or parameters • In the method call: • List of variables or expressions that match 1-1 with the parameters in the definition • Called actual parameters, or arguments CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  20. Writing Static Methods Ex: public static double area(double radius) { double ans = Math.PI * radius * radius; return ans; } … double rad = 2.0; double theArea = area(rad); • Note: If method is called in same class in which it was defined, we don’t need to use the class name in the call parameter argument CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  21. Parameters • Parameters in Java are passed by value • The parameter is a copy of the evaluation of the argument • Any changes to the parameter do not affect the argument answer calculated answer returned method completed area method Main Class value passed from arg. to parameter radius rad 2.0 2.0 result returned to main ans 12.566… theArea 12.566… double ans = Math.PI * radius * radius; double theArea = area(rad); main calls area method return ans; CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  22. More on Parameters • Effect of value parameters: • Arguments passed into a method cannot be changed within the method, either intentionally or accidentally • Good result: Prevents accidental side-effects from methods • Bad result: What if we want the arguments to be changed? • Ex: swap(A, B) • Method swaps the values in A and B • But with value parameters will be a “no-op” • We can get around this issue when we get into object-oriented programming CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  23. Local variables and scope • Variables declared within a method are local to that method • They exist only within the context of the method • This includes parameters as well • Think of a parameter as a local variable that is initialized in the method call • We say the scope of these variables is point in the method that they are declared up to the end of the method CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  24. Local variables and scope • However, Java variables can also be declared within blocks inside of methods • In this case the scope is the point of the declaration until the end of that block • Be careful that you declare your variables in the correct block • Demo on board CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  25. Local variables and scope • Note that either way, these variables cannot be shared across methods • We can still get data from one method to another • How? • To share variables across methods, we need to use object-oriented programming • We will see this soon! Return Statement CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  26. Recursion • A Java method can call any other public Java method • main() is just a method itself, and we have called other methods from it • Thus, a method should be able to call itself – we call this a RECURSIVE CALL • Since it is a method • At first thought this seems odd or even impossible – why would we want to do this? • However, it will be very useful in a lot of different programming approaches CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  27. Recursion • Before we look at the programming in detail, let’s try to get the idea down, using math • Some mathematical functions are in fact defined recursively • Example in text: Factorial N! = N * (N-1)! • Note that the function is defined in terms of itself, but with an important change: • The “recursive call” is smaller in size (N-1) than the original call (N) • This is vital to recursion being viable • Let’s trace 4! in this way to see what happens (see board) • Uh oh! CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  28. Recursion • What we are missing in the previous slide is a condition that allows the recursion to stop • Every recursive algorithm must have some terminating condition, to keep it from recursing “forever” • We call this the BASE CASE • What is the base case for factorial? • This now allows us to complete our algorithm: 0! = 1 N! = N * (N-1)! when N > 0N! = 1 when N = 0 CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  29. Recursion • Three important rules for any recursive algorithm: • There must be some recursive case, in which the algorithm “calls itself” • There must be some base case, in which no recursive call is made • The recursive calls must lead eventually to the base case • Usually by “reducing” the problem size in some way • Don’t forget these! CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  30. More Recursion • Let’s look at another example: • Calculating an integer power of another integer MN = • Don’t forget the base case MN = • The actions we take are slightly different from factorial, but the basic idea is similar • Trace this on board • Note how first call made is last call to complete • This is important in the implementation of recursion M * MN-1 N > 0 recursive case 1 N = 0 base case CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  31. Implementing Recursion • So how do we implement recursion? • Luckily the computer code is very similar to the mathematical functions • Consider factorial below • Note that the recursive call is made within the return statement • This is fine – return is done AFTER call completes public static int fact(int N) { if (N <= 1) return 1; else return (N * fact(N-1)); } CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  32. Implementing Recursion • How does recursion actually work? • Each time a method is called, an activation record (AR) is allocated for it • This consists of memory for the parameters and local variables used in the method • Each new activation record is placed on the top of the run-time stack • When a method terminates, its activation record is removed from the top of the run-time stack • Thus, the first AR placed onto the stack is the last one removed CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  33. Implementing Recursion N = 1 N <= 1? YES return fact(1) 1 N = 2 N <= 1? NO return (2 * fact(1)) = 1 fact(2) 2 N = 3 N <= 1? NO return (3 * fact(2)) = 2 fact(3) 6 N = 4 N <= 1? NO return (4 * fact(3)) = 6 fact(4) 24 24 CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  34. Recursion • Think about the Lab 2 using recursive function? • Recursive Case: • F (n) = F(n-1) + F(n-2) • Base Case: • F(1) = F(0) = 1 • The Recursive case will lead to base case • Final Code: • public static int Fibonacci ( int index) { if ( index == 0 || Index == 1) return 1; else return Fibonacci (index -1) + Fibonacci (index -2); } CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  35. Recursion vs. Iteration • Some recursive algorithms can also be easily implemented with loops • Both factorial and power can easily be done in this way • When possible, it is usually better to use iteration, since we don’t have the overhead of the run-time stack (that we just saw on the previous slide) • Other recursive algorithms are very difficult to do any other way • You will see more about recursion in CS 0445 • For now, let’s look at ex6.java CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

  36. Topics for next lecture • Reading Assignment: Chapter 5.1-5.8 You don’t need to know the details but you should know what are those when I talk about it. CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 4

More Related