* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Recursion
Survey
Document related concepts
Multiple-criteria decision analysis wikipedia , lookup
Molecular dynamics wikipedia , lookup
Horner's method wikipedia , lookup
Algorithm characterizations wikipedia , lookup
Newton's method wikipedia , lookup
Computational fluid dynamics wikipedia , lookup
Computational electromagnetics wikipedia , lookup
History of the Church–Turing thesis wikipedia , lookup
False position method wikipedia , lookup
Hardware random number generator wikipedia , lookup
Transcript
Chapter 6: Repetition Continued Validity Checks What’s weak about the following code? do { s1 = JOptionPane.showInputDialog (“Enter a number: ”); idNum = Integer.parseInt(s1); } While (idNum < 100 || idNum > 1999); 2 Alternative Code do { s1 = JOptionPane.showInputDialog (“Enter a number: ”); idNum = Integer.parseInt(s1); if (idNum < 100 || idNum > 1999) JOptionPane.showMessageDialog(null, “Error bla bla bla”, JOptionPane.ERROR_MESSAGE); else break; // a valid id num was entered } while (true); // expression is always true 3 Recursion • It is possible for a method to call itself • Methods that call themselves are referred to as: – Self-referential methods – Recursive methods • Direct recursion – A method invokes itself • Indirect or mutual recursion – A method can invoke a second method, which in turn invokes the first method 4 Mathematical Recursion • The recursive concept is that the solution to a problem can be stated in terms of “simple” versions of itself • Factorial of number n: – Denoted as n!, where n is a positive integer 1! = 1 n! = n * (n * 1)! for n > 1 5 Mathematical Recursion (continued) • General considerations that must be specified include: – What is the first case? – How is the nth case related to the (n - 1) case? 6 Pseudocode for Method factorial If n = 1 factorial = n Else factorial = n * factorial(n - 1) 7 Recursive Example public class Recursive { public static void main(String[] ags) { int n = 3; long result; result = factorial(n); System.out.println("The factorial of " + n + " is " + result); } public static long factorial(int n) { if (n == 1) return (n); else return (n * factorial(n-1)); } } 8 How the Computation Is Performed • A Java method can call itself due to: – Java’s allocation of new memory locations for all method arguments and local variables as each method is called • The allocation is made dynamically in a memory area referred to as the stack • The stack is memory used for rapidly storing and retrieving data 9 Recursion Versus Iteration • The recursive method can be applied to any problem in which the solution is represented in terms of solutions to simpler versions of the same problem • Recursive methods can always be written in a nonrecursive manner using an iterative solution 10 Recursion Versus Iteration (continued) • If a problem solution can be expressed iteratively or recursively with equal ease, the iterative solution is preferable because it: – Executes faster – Uses less memory • There are times when recursive solutions are preferable – Some problems are easier to visualize using a recursive algorithm – Sometimes a recursive solution provides a much simpler solution 11 Applications: Random Numbers and Simulations • Random numbers – Series of numbers whose order cannot be predicted – Hard to find in practice • Pseudorandom numbers – Sufficiently random for task at hand • Java compilers provide general-purpose method for creating random numbers – Defined in the Math class – Named random() 12 public class RandomNumbers { public static void main(String[] args) { double randValue; int i; for (i = 1; i <= 10; i++) { randValue = Math.random(); System.out.println(randValue); } } } 13 Scaling • A method for adjusting random numbers produced by a random number generator to reside within ranges, such as 1 to 100 – Accomplished using the expression: (int) (Math.random() * N) 14 Simulations • Common use of random numbers: – Simulate events rather than going through time and expense of constructing a real-life experiment • Coin Toss Simulation – Use random number generator to simulate coin tosses • Elevator Simulation – Simulate the operation of an elevator 15 Common Programming Errors • Creating a loop that is “off by one” • Repetition statements should not test for equality when testing floating-point (real-values) operands • Placing a semicolon at the end of either a while or for loop’s parentheses • Using commas to separate items in a for statement instead of the required semicolons • Omitting a final semicolon from a do-while statement 16 Summary • A section of repeating code is referred to as a loop – Types of loops: • while • for • do-while • A while statement checks a condition before any other statement in a loop 17 Summary (continued) • A for statement is extremely useful in creating loops that must be executed a fixed number of times • A do-while statement checks its expression at the end of the loop 18