Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6: Repetition Continued. 2 Validity Checks What’s weak about the following code ? do { s1 = JOptionPane.showInputDialog (“Enter a number: ”);

Similar presentations


Presentation on theme: "Chapter 6: Repetition Continued. 2 Validity Checks What’s weak about the following code ? do { s1 = JOptionPane.showInputDialog (“Enter a number: ”);"— Presentation transcript:

1 Chapter 6: Repetition Continued

2 2 Validity Checks What’s weak about the following code ? do { s1 = JOptionPane.showInputDialog (“Enter a number: ”); idNum = Integer.parseInt(s1); } While (idNum 1999);

3 3 Alternative Code do { s1 = JOptionPane.showInputDialog (“Enter a number: ”); idNum = Integer.parseInt(s1); if (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

4 4 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

5 5 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

6 6 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?

7 7 Pseudocode for Method factorial If n = 1 factorial = n Else factorial = n * factorial(n - 1)

8 8 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)); } }

9 9 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

10 10 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 non- recursive manner using an iterative solution

11 11 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

12 12 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()

13 13 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); } } }

14 14 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)

15 15 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

16 16 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

17 17 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

18 18 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


Download ppt "Chapter 6: Repetition Continued. 2 Validity Checks What’s weak about the following code ? do { s1 = JOptionPane.showInputDialog (“Enter a number: ”);"

Similar presentations


Ads by Google