Download presentation
Presentation is loading. Please wait.
1
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 15: Nov 28-Dec 2, 2011 Aditya Mathur Department of Computer Science Purdue University West Lafayette, IN, USA http://www.cs.purdue.edu/homes/apm/courses/CS180Fall2011/ This Week: 11/28-30 1.Exceptions 2.Recursion 3.Dynamic data structures
2
Readings and Exercises for Week 15 Readings: Chapter: 8.4, 12.1, 12.2, 12.3; 18.1, 18.8 Exercises: 8.6, 12.2, 12.3, 18.1, 18.10 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 2
3
Announcements Project 5 due on Tuesday Dec 6, 11:59pm. Implement incrementally. Please DO attend the class on Monday Dec 5. Programming competition. Chief Guest Dr. Tim Korb. Details of Final Exam on Wednesday Dec 7. Please complete course evaluation. Thanks. Special class. Sunday Dec 11, 2011. 4pm. LWSN 3102AB 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 3
4
Average: 75.8 Median: 83 Std Dev: 21.44 A+: 100/98 A: 97/94 A-: 93/90 B+: 89/87 B: 86/82 B-: 81/78 C+: 77/73 C: 72/67 C-: 66/56 D: 55/40 F: 39/0 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 4 Exam 2 Statistics
5
Exceptions 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 5
6
Exceptions An abnormal or unexpected condition during execution. When such a condition occurs, Java run time system does not always know how best to proceed and hence raises an exception. Some exceptions must be explicitly handled by the programmer. 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 6
7
Exception: Example 1 public class ExceptionExampleDiv0{ public static void main(String [] args){ int y=1, z=0; int x=y/z; } java.lang.ArithmeticException: / by zero at ExceptionExampleDiv0.main(ExceptionExampleDiv0.java:8) 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 7
8
Exception: Example 2 public class ExceptionExampleDiv0{ public static void main(String [] args){ int y=1, z=0; try{ int x=y/z; }catch(ArithmeticException e){ System.out.println(“Divide by zero:”+e); } } Divide by zero java.lang.ArithmeticException: / by zero Try-catch not required 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 8
9
Exception: Unchecked (or Error) Arise during runtime due to some programming error. Not flagged by the compiler. Programmer may choose to handle these. Not subject to Catch requirement. Examples: ArithmeticException ArrayIndexOutOfBounds NullPointerException 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 9
10
Exception: Example 3 public class ExceptionExampleFile{ public static void main(String [] args){ File f=new File("test.txt"); Scanner source=new Scanner(f); } 1 error found: File: /Users/apm/www/courses/CS180Fall2010/Notes/Programs/Exc eptions/ExceptionExampleFile.java [line: 8] Error: /Users/apm/www/courses/CS180Fall2010/Notes/Programs/Exc eptions/Except 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 10
11
Exception: Example 4 public class ExceptionExampleFile{ public static void main(String [] args){ File f=new File("test.txt"); try{ Scanner source=new Scanner(f); }catch(FileNotFoundException e){ System.out.println("File not found "+e); } File not found java.io.FileNotFoundException: test.txt (No such file or directory) 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 11
12
Exception: Checked exceptions These are subject to the catch requirement. Programmer is expected to write code to recover from these exceptions. Example: FileNotFoundException 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 12
13
Exception: try-catch try{ code where exception might occur; }catch(exception object){ code to handle exception } catch-block try-block A catch-block serves as an exception handler. 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 13
14
Exception: try-catch: multiple catch blocks try{ code where exception might occur; }catch(exception object){ code to handle exception; }catch(another exception object){ code to handle exception; } catch-block try-block Another catch- block 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 14
15
Exception: try-catch-finally try{ Code where exception might occur; }catch(exception object){ code to handle exception; }finally{ code to handle exception; } catch-block try-block finally-block finally-block always executes after the try-catch blocks (unless the program exits prior to the control arriving at the finally block). 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 15
16
Exception: Not handled public ExceptionTest(){ Scanner s=new Scanner(new File (“DoesNotExist”)); } Error: /Users/apm/www/courses/CS180Fall2011/Notes/Programs/Recur sion/Tree/ExceptionTest.java:7: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 16
17
Exception: Throwing public ExceptionTest() throws Exception{ Scanner s=new Scanner(new File (“DoesNotExist”)); } This will compile…. BUT… 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 17 A method…NOT a class…can throw an Exception.
18
Exception: Throwing but not handling later public ExceptionTest() throws Exception{ Scanner s=new Scanner(new File (“DoesNotExist”); } Error: /Users/apm/www/courses/CS180Fall2011/Notes/Programs/Recur sion/Tree/ExceptionTest.java:11: unreported exception java.lang.Exception; must be caught or declared to be thrown… 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 18 public static void main(String [] arg){ new ExceptionTest(); }
19
Exception: Throwing but handling later public ExceptionTest() throws Exception{ Scanner s=new Scanner(new File (“DoesNotExist”); } 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 19 public static void main(String [] arg){ try{ new ExceptionTest(); }catch(Exception e){ }
20
Recursion 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 20
21
What is recursion? We say that a method is recursive, when it calls itself. This is known as direct recursion. Recursion is a technique to code functions (or methods) in Java. Indirect recursion occurs when a method is called, before it completes, by another method. Recursion is complementary to iteration. While solving a problem, you may choose to use either. 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 21
22
Example: Factorial !n= 1, if n=0 or 1 = 1*2*3*…*n; Definition: Iterative [n>=0] !n= 1, if n=0 or 1 = n*!(n-1), if n>1 Definition: Recursive [n>=0] Basis Recursion 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 22
23
Example: Factorial: Iterative method !n= 1, if n=0 or 1 = 1*2*3*…*n; otherwise Definition: Iterative [n>=0] public int factIter(int n){ if(n==0 || n==1) return 1; int prod=1; for (int i=2; i<=n; i++){ prod=prod*i; } return (prod); } !5=prod=1*2*3*4*5 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 23
24
Example: Factorial: Recursive method public int factRecur(int n){ if(n==0 || n==1){ return 1; }else{ return (n*factRecur(n-1)); } !n= 1, if n=0 or 1 = n*!(n-1), if n>1 Definition: Recursive [n>=0] factRecur(5)=5*factRecur(4)*factRecur(3)*factRecur(2)*factRecur(1) =5*factRecur(4)*factRecur(3)*factRecur(2)*1 =5*factRecur(4)*factRecur(3)*2*1 =5*factRecur(4)*3*2*1 =5*4*3*2*1 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 24
25
Recursion versus Iteration Iteration suffices for most problems that arise in practice. However, in some cases recursion allows compact and quick solution. An example follows. 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 25
26
Announcements Feast with faculty today at 6:30pm Ford Dining Hall. All are welcome. Project 4 grades are on Blackboard. If your submitted program was working but you received a low grade then please contact TA Julian Stephen. Programming competition: Round 2: Saturday 6pm. LWSN 3102. Three teams will be selected for the final round. 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 26
27
Towers of Hanoi: The problem Given: Three towers A, B, and C. A contains n discs arranged from bottom to top as shown below. Problem: Find a sequence of moves such that at the end of these moves all discs are in C. No larger disc should ever be on top of a smaller disk. Only one disk can be moved at a time from one tower to another. Only the top disc can be moved from a tower. ABC 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 27
28
Towers of Hanoi: Initial and final configurations ABC Initial configuration ABC Final configuration 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 28
29
Towers of Hanoi: Iterative solution Try this! This will be difficult but certainly worth a try. 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 29
30
Towers of Hanoi: Recursive solution What is a move? Only one disc can be moved from one tower to another. Hence we will write a move as: moveADisc (TA, TB); TA is the tower from where the top disc is moved and placed on top in tower TB. move (TA, TB, TC, n); This will move n discs from tower TA to tower TB via tower TC while ensuring the constraints. 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 30
31
Towers of Hanoi: Recursive solution: Visualization BCA Start 1 BCA 2 BCA 3 BCA 4 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 31
32
Towers of Hanoi: Recursive program: Live 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 32
33
Towers of Hanoi: Challenge! How many moves are required to move n discs from tower A to tower C? 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 33
34
Recursion and Dynamic data structures 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 34
35
Dynamic data structures Useful when size of the data structure is not known in advance. Useful for designing efficient algorithms. 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 35 Examples: Stack, Linked list, binary tree, etc. In Java: ArrayList, Vector Static data structure: Array
36
Tree (Binary) 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 36 Tree with one node (the root) Left link Right link Tree with a root linked to two other nodes. Left link Right link Another tree.
37
Tree: with data 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 37 Tree with one node (the root) 25 Left link Right link Tree with a root linked to two other nodes. 25 14 39 Left link Right link Another tree. 25 39 14 9 Do you see a pattern?
38
Tree: Binary search 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 38 Left link Right link 25 39 14 9 Does x exist in the tree? boolean find(int x, Node root){ if(x is at the root) return true; if (x< value at the root) return find (x, root.leftLink); else return find(x, root.rightLink); }
39
Binary search tree: Creation 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 39 Add 39. This is greater than the number at the root. Hence add a new node to the right subtree. 25 39 Add 14. As this is less than the value at the root, add a new node to the left of the root. Left link Right link 25 39 14 Add 25. Start with an empty tree and add a node. Set root to be this node. 25 Left and right links are null. Each data item exists exactly once in the tree.
40
Tree: Non-empty binary search tree 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 40 Has a root Each node has 0, 1, or 2 links. Links are generally termed as left and right links. Each node has a data item in it. Suppose that node n points to nodes n1 (left) and n2 (right). Then the data at node n1 is less than that at n and the data at node n2 is greater than that at node n.
41
Binary search tree creation: Exercise 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 41 What will a binary search tree look like after the following numbers are added in this sequence given: 5, 29, -4, 23, 99, 3?
42
Live demo: Tree creation and traversal. 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 42
43
Week 15: November 28-Dec 2, 2011 Hope you enjoyed this week! Questions? Contact your recitation instructor. Make full use of our office hours. 11/28/2011 ©Aditya Mathur. CS 180. Fall 2011. Week 15 43
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.