Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Programming G51PRG University of Nottingham Revision 3 Essam Eliwa.

Similar presentations


Presentation on theme: "Introduction to Programming G51PRG University of Nottingham Revision 3 Essam Eliwa."— Presentation transcript:

1 Introduction to Programming G51PRG University of Nottingham Revision 3 Essam Eliwa

2 Methods 1. Most problems naturally break down into sub-problems. 2. Large problems must be implemented by a team, not an individual. 3. 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 1. Modifiers, such as public, private, and others you will learn about later. 2. return type, the data type of the value returned by the method, or void if the method does not return a value. 3. Method name 4. The parameter list in parenthesis. a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). 5. An exception list (more details later) 6. 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 method1mainmethod2 method1(); Method2();

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 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 method No code outside a method can see the local variables inside another method. Lifetime: From method call to method return Local 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: None Local 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 variables Method 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 class Factorial { int fact(int n) { int result; if ( n ==1) return 1; //stop condition result = fact (n-1) * n; return result; } Assume we call the fact method with value 5 fact(5);

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

25 Tracing Factorial fact (n-1) result = methodReturn * n; n=5 result=? n=4 result=? n=3 result= ? n=2 result= ? n=1 result= 1 1 2 3 4 5 10 9 8 7 6 n=5 result=120 n=4 result=24 n=3 result=6 n=2 result= 2 n=1 result= 1 Return 1 Return 2 Return 6 Return 24 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


Download ppt "Introduction to Programming G51PRG University of Nottingham Revision 3 Essam Eliwa."

Similar presentations


Ads by Google