Java Reference
In-Depth Information
Self-Test Exercises
1. What is the output of the following program?
public class Exercise1
{
public static void main(String[] args)
{
cheers(3);
}
public static void cheers( int n)
{
if (n == 1)
{
System.out.println("Hurray");
}
else
{
System.out.println("Hip ");
cheers(n 1);
}
}
}
2. Write a recursive void method that has one parameter which is a integer and that
writes to the screen the number of asterisks '*' given by the argument. The out-
put should be all on one line. You can assume the argument is positive.
3. Write a recursive void method that has one parameter, which is a positive integer.
When called, the method writes its argument to the screen backward. That is, if
the argument is 1234 , it outputs the following to the screen:
4321
4. Write a recursive void method that takes a single (positive) int argument n and
writes the integers 1 , 2 , . . . , n to the screen.
5. Write a recursive void method that takes a single (positive) int argument n and
writes integers n , n-1 , . . . , 3 , 2 , 1 to the screen. Hint: Notice that you can get from
the code for Self-Test Exercise 4 to that for this exercise (or vice versa) by an
exchange of as little as two lines.
Stacks for Recursion
To keep track of recursion, and a number of other things, most computer systems use a
structure called a stack. A stack is a very specialized kind of memory structure that is anal-
ogous to a stack of paper. In this analogy, there is an inexhaustible supply of extra blank
sheets of paper. To place some information in the stack, it is written on one of these
sheets of paper and placed on top of the stack of papers. To place more information
stack
Search WWH ::




Custom Search