Java Reference
In-Depth Information
Display 11.2 Iterative Version of the Method in Display 11.1
1 public static void writeVertical( int n)
2 {
3 int nsTens = 1;
4 int leftEndPiece = n;
5 while (leftEndPiece > 9)
6 {
7 leftEndPiece = leftEndPiece / 10;
8 nsTens = nsTens * 10;
9 }
10 //nsTens is a power of 10 that has the same number
11 //of digits as n. For example, if n is 2345, then
12 //nsTens is 1000.
13 for ( int powerOf10 = nsTens;
14 powerOf10 > 0; powerOf10 = powerOf10 / 10)
15 {
16 System.out.println(n / powerOf10);
17 n = n % powerOf10;
18 }
19 }
Self-Test Exercises
6. If your program produces an error message that says stack overfl ow , what is a
likely source of the error?
7. Write an iterative version of the method cheers defi ned in Self-Test Exercise 1.
8. Write an iterative version of the method defi ned in Self-Test Exercise 2.
9. Write an iterative version of the method defi ned in Self-Test Exercise 3.
10. Trace the recursive solution you made to Self-Test Exercise 4.
11. Trace the recursive solution you made to Self-Test Exercise 5 .
11.2
Recursive Methods That Return a Value
To iterate is human, to recurse divine.
ANONYMOUS
 
 
Search WWH ::




Custom Search