1 / 26

Introduction to Programming G51PRG University of Nottingham Revision 3

Introduction to Programming G51PRG University of Nottingham Revision 3. Essam Eliwa. Methods. Most problems naturally break down into sub-problems. Large problems must be implemented by a team, not an individual. Reusability of the parts, is highly appreciated For the program itself

tambre
Download Presentation

Introduction to Programming G51PRG University of Nottingham Revision 3

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. Introduction to ProgrammingG51PRGUniversity of NottinghamRevision 3 Essam Eliwa

  2. Methods • Most problems naturally break down into sub-problems. • Large problems must be implemented by a team, not an individual. • Reusability of the parts, is highly appreciated • For the program itself • For other programs

  3. Defining Methods • The only required elements of a method declaration are: • the method's return type • the method's Name • a pair of parentheses, ( ) • a body between braces, { } Return_type methodName(optional_parameters) { //method Body here }

  4. Method declarations components • Modifiers, such as public, private, and others you will learn about later. • return type, the data type of the value returned by the method, or void if the method does not return a value. • Method name • The parameter list in parenthesis. a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). • An exception list (more details later) • The method body, enclosed between braces—the method's code, including the declaration of local variables.

  5. Naming a Method • a method name can be any legal identifier • By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb • In multi-word names, the first letter of each of the second and following words should be capitalized • Examples: • addNumbers • moveShape • isFound • print

  6. Examples of method declarations class Count { public static void count(int maxNum){ int count=0; do{ System.out.println("Count is: " + count); count++; } while (count < maxNum) }//count method end }//class end • This code will do nothing so far, we defined the method, However, we must have a call statement to execute it

  7. Method Call class Count { public static void count(int maxNum){ int count=0; do{ System.out.println("Count is: " + count); count++; } while (count < maxNum) }//count method end public static void main(String[] args){ count(10); }//main end }//class end • For now, all methods we use have to be static (more on that latter)

  8. Method Flow of Control • The main method is invoked by the system when you run your program • Each method call returns to the place that called it main method1 method2 Method2(); method1();

  9. The method definition • we need to identify each of the parameters (if needed), so that we can refer to them and use them from within the code which forms the body of the method. • it is conventional to declare any local variables at the start of the body (apart from loop variables). a new copy of them is created every time a method is called (invoked). • The rest of the body of the method is dedicated to implementing the logic of the method so that it performs the job we want it to. This can include any java legal statements. • At any point we can exit the method using a return statement

  10. Example • Read a list of numbers from the user and print only the highest number. • Method needed: • readNumbers • findMax • printMax

  11. printMax public static void printMax(int max){ System.out.println("The maximum value entered was " + max); }//printMax end

  12. findMax public static int findMax(int num1, int num2) { int max=0; if(num1>num2){ max=num1; } else{ max=num2; } return max; }

  13. readNumber public static int readNumber() { count++; UserInput.prompt("Enter number " + count + ": "); return (UserInput.readInt()); }

  14. Max Program public class Max { static int count=0; ………………………..//methods here public static void main(String[] args){ int number=0; int max=0; while(number!=-1) { number = readNumber(); max = findMax(max,number); } printMax(max); } }

  15. Example 2 • Write a program to print the Mean Value of a set of numbers entered by the user • We can Reuse readNumber Method • Other Method needed: • clacMean • printMean

  16. readNumber public static int readNumber() { count++; UserInput.prompt("Enter number " + count + ": "); return (UserInput.readInt()); }

  17. calcMean public static int clacMean(int total, int count) { return total/count; }

  18. printMean public static void printMean(int mean){ System.out.println("The mean value is " + mean); }//printMean end

  19. Mean Program public class Mean { static int count=0; static final int COUNTMAX=5; ……….//methods here public static void main(String[] args){ int total=0; int mean=0; do{ total+= readNumber(); }while(count<COUNTMAX); mean = clacMean(total, count); printMean(mean ); } }

  20. Method Local variables • Visibility: Only in defining methodNo code outside a method can see the local variables inside another method. • Lifetime: From method call to method returnLocal variables are created on the call stack when the method is entered, and destroyed when the method is exited. You can't save values in local variables between calls. For that you have to use instance variables, which you'll learn about a little later. • Initial value: NoneLocal variables don't have initial values by default -- you can't try to use their value until you assign a value. It's therefore common to assignment a value to them when they're declared.

  21. Method Local variables • Parameters are pre-initialized local variablesMethod parameters are basically implemented as local variables. They have the same visibility and lifetime.

  22. Recursion • Simply, recursion is when a function calls itself. • The arguments passed to the recursion take us closer to the solution with each call • The key to thinking recursively is to see the solution to the problem as a smaller version of the same problem • Every recursion should have the following characteristics. • A simple base case which we have a solution for and a return value. • A way of getting our problem closer to the base case. • A recursive call which passes the simpler problem back into the method.

  23. Factorial • Assume we call the fact method with value 5 • fact(5); class Factorial {      int fact(int n) {          int result;      if ( n ==1) return 1; //stop condition      result = fact (n-1) * n;      return result;      } }

  24. n=1 result= 1 n=1 result= 1 5 6 n=2 result= ? n=2 result= 2 4 7 n=3 result= ? n=3 result=6 3 8 n=4 result=? n=4 result=24 2 9 n=5 result=? n=5 result=120 1 10 Tracing Factorial if ( n ==1) return 1; //base case Return 1 Return 2 Return 6 fact (n-1) Return 24 result = fact (n-1) * n; //recursive call Return 120

  25. Tracing Factorial n=1 result= 1 n=1 result= 1 6 5 Return 1 n=2 result= ? n=2 result= 2 4 7 result = methodReturn * n; Return 2 n=3 result= ? n=3 result=6 3 8 Return 6 fact (n-1) n=4 result=? n=4 result=24 2 9 Return 24 n=5 result=? n=5 result=120 1 10 Return 120

  26. Exam Hints • printMenu() Method • You will need to use switch-case for menu choices • You will need a loop to rerun your menu till the user chooses to exit • Use “static final” if needed • Course Marker checks the whole method signature not just the name

More Related