Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 106 Introduction to Computer Science I 10 / 11 / 2006 Instructor: Michael Eckmann.

Similar presentations


Presentation on theme: "CS 106 Introduction to Computer Science I 10 / 11 / 2006 Instructor: Michael Eckmann."— Presentation transcript:

1 CS 106 Introduction to Computer Science I 10 / 11 / 2006 Instructor: Michael Eckmann

2 Michael Eckmann - Skidmore College - CS 106 - Fall 2006 Today’s Topics Comments and/or Questions? Math.random() quick review. programmer defined methods –terminology –parameters –local variables –calling a method –program control sorting

3 random( ) method in the Math class what does Math.random ( ) return?

4 random( ) method in the Math class Math.random ( ) returns a double whose value is >= 0 and < 1.

5 random( ) method in the Math class // example: int some_random_int; some_random_int = 2*(7 + (int) (Math.random ( ) * 4)); // what are the possible values for some_random_int here?

6 random( ) method in the Math class // example: int some_random_int; some_random_int = 2*(7 + (int) (Math.random ( ) * 4)); // what are the possible values for some_random_int here? (int) (Math.random ( ) * 4) gives 0, 1, 2, or 3 7 + (0, 1, 2, or 3) gives 7, 8, 9 or 10 2*(7,8,9,or 10) gives 14, 16, 18 or 20

7 what is a method A method is small piece of a program designed to achieve some specific task and usually returns some piece of information. A method is invoked by a method call. To call a method, you provide its name and the correct arguments that are necessary for the method to execute. Michael Eckmann - Skidmore College - CS 106 - Fall 2006

8 methods Here’s a good analogy of a worker and boss to describe methods and their callers. A boss (the caller) asks a worker (the method that is called) to perform a task (the code in the method) and report (return results) back when the task is done. Michael Eckmann - Skidmore College - CS 106 - Fall 2006

9 methods All methods are defined within some class. we have seen the main method defined in the class of every application so far. Michael Eckmann - Skidmore College - CS 106 - Fall 2006

10 other methods we’ve used We have called other methods available in the Java API, methods like parseInt and parseFloat and println are available to us to use in their respective classes Integer, Float and System.out The methods in the Math class are other examples. These methods were defined for us to do a specific task. We call them when we need them. e.g. in the case of Integer.parseInt --- it’s task is to convert a String into an int. It takes a String as an argument and returns a value of type int. Michael Eckmann - Skidmore College - CS 106 - Fall 2006

11 other methods we’ve used example of a call to this method: some_int = Integer.parseInt( some_str ); In this example, some_str is the argument that is being passed in to the parseInt method and some_int is the variable that will get set to the value returned by the method. Michael Eckmann - Skidmore College - CS 106 - Fall 2006

12 methods We can create our own methods that we can call to perform specific tasks. Let’s say we’re writing a program to handle employee’s salaries. We might need to compute a salary after a raise. This example method would need to have access to the current salary and the raise percentage. It would then calculate the salary after the raise and return this value. Michael Eckmann - Skidmore College - CS 106 - Fall 2006

13 example of a programmer-defined method we might name this method salary_after_raise we need to take in two values, one for the current salary and one for the raise percentage. What primitive type might these be? we also need to return the salary that is computed. What primitive type might this returned value be? Michael Eckmann - Skidmore College - CS 106 - Fall 2006

14 example of a programmer-defined method so, this method could look like: public static double salary_after_raise(double curr_sal, double raise_pct ) { double new_sal; new_sal = curr_sal * ( 1 + raise_pct / 100 ); return new_sal; } Michael Eckmann - Skidmore College - CS 106 - Fall 2006

15 example of a programmer-defined method to call this method from some other method within the same class do the following: // example variable declarations... double new_salary; double old_sal = 35000; double raise = 4.5; // our call to the salary_after_raise method new_salary = salary_after_raise( old_sal, raise ); Michael Eckmann - Skidmore College - CS 106 - Fall 2006

16 example of a programmer-defined method Let’s look at a complete program that contains this method and calls it several times. Michael Eckmann - Skidmore College - CS 106 - Fall 2006

17 example of a programmer-defined method When certain code can be used in several places in a program, you may want to create a method containing that code. Then, wherever that code would have been, a simple method call appears. Programmer defined methods also aid in the ability to understand a program (readability) and make changes. Michael Eckmann - Skidmore College - CS 106 - Fall 2006

18 when does a method end it’s execution? when it hits a return; statement when it hits a return some_expression; statement or, when it hits the right curly brace of the method whichever comes first. when the method ends its execution, the program execution continues at the method call

19 more about methods methods that do not return a value are of type void (like the main method.) Method can have 0 or more parameters seperated by commas. Those with 0 parameters are defined with nothing between the parentheses to call a method with no parameters, you must still use the parentheses but with nothing between them Note that the return type of a method can be different than any or all of the types of parameters that get passed in.

20 example method that returns nothing and has no parameters public static void print_error_msg() { System.out.println(“Invalid entry.”); System.out.println(“You must reenter.”); } how to call this method: note that there are no arguments passed in nor is there a variable to which to assign the returned value (because it doesn’t return a value.) print_error_msg();

21 example method that returns nothing but has one parameter public static void print_msg(String the_msg) { System.out.println(“The message is: ” + the_msg); // note: no return statement since nothing to return // The return type of this method is void. } how to call this method: print_msg(“Good afternoon gentlemen. I am a HAL 9000 computer.”); // name the film.

22 example method that returns a String but has no parameters public static String random_string() { int num = (int) (Math.random() * 3); if (num == 0) return “Hello”; if (num == 1) return “Goodbye”; if (num == 2) return “$#@&!*”; } how to call this method: System.out.println(“the random string is: “ + random_string());

23 reasons to create and use methods separation and modularization of ideas is helpful when writing large programs because smaller parts of a problem are easier to solve the individual methods can be tested and confirmed correct to reduce debugging woes methods lend themselves to software reusability less code repetition more readable, better designed code

24 scope the scope of an identifier (a variable, reference or method name) is defined as the portion of the program that can access that identifier the two scopes for identifiers are class scope and block scope class scope starts at the opening left curly brace of a class definition and ends at its corresponding right curly brace block scope refers to identifiers that are accessible from when they are declared until the next right curly brace.

25 variables in methods variables declared in methods are said to be local variables --- they are local to that method parameters of the method are also considered local variables to that method. they are not usable, nor are they even known outside that method --- they have block scope they are created (memory is allocated for them) on entry into the method during execution they are destroyed (memory for them is marked for deallocation) on exit from the method

26 some method terminology the name of the method is salary_after_raise, and the body of the method is the three lines of code between the curly braces. public double salary_after_raise(double curr_sal, double raise_pct) { double new_sal; new_sal = curr_sal * ( 1 + raise_pct / 100 ); return new_sal; }

27 example of local variables in this method, new_sal is a local variable, and the parameters of the method: curr_sal and raise_pct are also local variables. public double salary_after_raise(double curr_sal, double raise_pct) { double new_sal; new_sal = curr_sal * ( 1 + raise_pct / 100 ); return new_sal; } they are only known to this method what does that mean “only known to this method”

28 return type and argument types the return type of the method is double, and the two parameters are of type double. public double salary_after_raise(double curr_sal, double raise_pct ) { double new_sal; new_sal = curr_sal * ( 1 + raise_pct / 100 ); return new_sal; } note that the return statement returns the double and this is where the execution of the method ends

29 method calls in the call of the method, two values are passed in to the method (we call them the arguments) and the value returned by the method call is stored in new_salary double new_salary; double old_salary = 300; double raise = 4.5; // our call to the salary_after_raise method new_salary = salary_after_raise( old_salary, raise );

30 variables passed in as arguments when calling a method the values of variables (of primitive types) that are passed into a method as arguments remain unchanged even if the corresponding parameter in the method changes its value, this change is only local to the method, and the value is not “passed back out” of the method. we’ll see this in the factorial method on the next slide.

31 compute_factorial method public int compute_factorial(int num) { int temp_factorial=1; while (num > 0) { temp_factorial = temp_factorial * num; num--; } return temp_factorial; }

32 compute_factorial method this method is a programmer-defined method (that is, we make up the name and the purpose of the method.) the name of the method is: compute_factorial the return type of the method is: int there is one parameter to the method, which is: num (of type int) note that the value of num inside the method changes (it gets decremented in the loop) but this is only a local change the other local variable (temp_factorial) is used to compute the factorial and its value is the one that is returned to the caller.

33 compute_factorial method note that the value of num inside the method changes (it gets decremented in the loop) but this is only a local change Let’s write a quick program to show how the variable that is “passed in” to the method as an argument doesn’t actually get changed. We’ll print the argument’s value before and after the call to the method.

34 promotion of argument types if a method is called with arguments of types different from those specified in the parameter list of the method definition, then Java will try to convert the value to the required type. The conversion is done according to Java’s promotion rules Java only allows conversions such that no information would be lost by the type conversion. If information would be lost, then a compiler error would result.

35 promotion of argument types some valid type conversions: –a float can be passed in to a method requiring a double –an int can be passed in to a method requiring a long, or a float or a double some type conversions that would cause compiler errors: –a float cannot be passed in to a method requiring an int –a double cannot be passed in to a method requiring a float

36 a method call with the wrong type public int test_value(double input_val) { if (input_val < 0) return –1; else return 1; } Example call in some other method: int length = 3; int returned_val; returned_val = test_value(length); // call is allowed: int length is promoted to double;

37 a method to find the smallest of 4 ints we’ll write a method to find the smallest of four integers (not in an array) and return that value. what might we call this method? what will the parameter list be? will we return a value? if so, what type? will we need any local variables besides the parameters? Let's write your ideas on the board.

38 a method to find the smallest of 4 ints public int smallest_of4(int num1, int num2, int num3, int num4) { int smallest; if (num1 < num2) // compare the first two smallest = num1; else smallest = num2; if (num3 < smallest) // compare the 3rd against the smallest so far smallest = num3; if (num4 < smallest) // compare the 4th against the smallest so far smallest = num4; return smallest; }

39 example call of this method int int1=14, int2=-9, int3=10, int4=879; int least; least = smallest_of4(int1, int2, int3, int4); // least will contain the value -9

40 Sorting Sorting is a large topic in some computer science courses. We'll discuss what sorting is and at least two algorithms for doing it. There are a myriad of ways to sort. Arrays of data lend themselves easily to being sorted. Sorting can be done in ascending or descending order.

41 Sorting Original unsorted: 38, 41, 22, 12, 67 We want the list to be: 12, 22, 38, 41, 67 To accomplish this, one way would be to: – Go through the whole list once and find the lowest value. – Take it out and put it in a new list. – Go through the remaining list of numbers and find the lowest and take it out – Take that one out and put it at the end of the new list. – And so on... until there's nothing left in the list. Does everyone agree that this will achieve a sorted list. We didn't say how exactly we'd find the lowest value each time --- the next slide describes a different way to sort and is more detailed.

42 Sorting Another way would be to: – compare the number in the first position to all the other numbers in the list and swap them in place if the number in the first position is greater than the number in the other position. – the second pass does the same thing but with the number in the second position. – third pass does the same but with the 3 rd number. – and so on, until the last position is reached. Why would this work or not work?

43 Sorting This algorithm doesn’t require a new list like the first one mentioned. All the sorting is done within the one list. After the first pass, what is guaranteed about the list? After the second pass, what is guaranteed about the list? Etc.

44 Sorting Original unsorted: 38, 41, 22, 12, 67 compare 38 to 41. 38 is not > 41, so leave them in place. compare 38 to 22. Swap them. So, now list is 22, 41, 38, 12, 67 compare 22 to 12. Swap them. So, now list is 12, 41, 38, 22, 67 compare 12 to 67. 12 is not > 67, so leave them in place. After first pass: 12, 41, 38, 22, 67

45 Sorting After first pass: 12, 41, 38, 22, 67 Now start at second position. compare 41 to 38. Swap them. So, now list is 12, 38, 41, 22, 67 compare 38 to 22. Swap them. So, now list is 12, 22, 41, 38, 67 compare 22 to 67. Leave them. After second pass: 12, 22, 41, 38, 67

46 Sorting After second pass: 12, 22, 41, 38, 67 Now start at third position. compare 41 to 38. Swap them. So, now list is 12, 22, 38, 41, 67 compare 38 to 67. Leave them. After third pass: 12, 22, 38, 41, 67

47 Sorting After third pass: 12, 22, 38, 41, 67 Now start at fourth position. compare 41 to 67. Leave them. After fourth pass: 12, 22, 38, 41, 67 Done now.

48 Sorting (BubbleSort) Another algorithm for sorting is the BubbleSort: – Compares consecutive numbers in the list – Swaps them if the two numbers are not in ascending order – Compare each consecutive pair of numbers in the first pass. – Next pass, start at first again but go only up until the next to last element, and so on… – Do n – 1 passes, where n is length of the list

49 Sorting (BubbleSort) Original unsorted: 38, 41, 22, 12, 67 compare 38 to 41. 38 is not > 41, so leave them in place. compare 41 to 22. Swap them. So, now list is 38, 22, 41, 12, 67 compare 41 to 12. Swap them. So, now list is 38, 22, 12, 41, 67 compare 41 to 67. Leave them. After first pass: 38, 22, 12, 41, 67

50 Sorting (BubbleSort) After first pass: 38, 22, 12, 41, 67 Now start at first position again. compare 38 to 22. Swap them. So, now list is 22, 38, 12, 41, 67 compare 38 to 12. Swap them. So, now list is 22, 12, 38, 41, 67 compare 38 to 41. Leave them. (don't need to compare the 4th and 5th positions) – why??? After second pass: 22, 12, 38, 41, 67

51 Sorting (BubbleSort) After second pass: 22, 12, 38, 41, 67 Now start at first position again. compare 22 to 12. Swap them. So, now list is 12, 22, 38, 41, 67 compare 22 to 38. Leave them. After third pass: 12, 22, 38, 41, 67

52 Sorting (BubbleSort) After third pass: 12, 22, 38, 41, 67 Now start at first position again. compare 12 to 22. Leave them. Done. After fourth pass: 12, 22, 38, 41, 67


Download ppt "CS 106 Introduction to Computer Science I 10 / 11 / 2006 Instructor: Michael Eckmann."

Similar presentations


Ads by Google