public static void countdown(int n) {
System.out.println(n);
if (n>1) {
countdown(n-1);
}
}
Output (n = 10):
10
9
8
7
6
5
4
3
2
1
Thoughts: - Seems simple enough. The method prints the number passed in, calls itself passing to itself that same
number reduced by one and stops calling itself when n is equal to 1.
b. Countup:
public static void countup(int n) {
if (n>1) {
countup(n-1);
}
System.out.println(n);
}
Output (n = 10):
1
2
3
4
5
6
7
8
9
10
Thoughts: - Wait a minute! Why do the numbers count down? The answer is found in tracing a recursive method
which we will discuss below.
4
6
2
7
Psuedocode for the recursive method is as follow:
// Printing the digits of a non-negative number, stacked vertically
if (the number has only one digit)
Write that digit.
else {
Write the digits of number/10 stacked vertically.
Write the single digit of number % 10.
}
Actual Code:
public static void writeVertical(int number) {
if (number < 10)
System.out.println(number); // Write the one digit.
else
{
writeVertical(number/10); // Write all but the last digit.
System.out.println(number % 10); // Write the last digit.
}
}
Terminology:
if (number < 10)
System.out.println(number); // Write the one digit.
else
{
writeVertical(number/10); // Write all but the last digit.
System.out.println(number % 10); // Write the last digit.
}
writeVertical(375);
Call | number | which case (recursive, stopping, or return)? | output this call | next recursive call | on the stack |
---|---|---|---|---|---|
writeVerical(375) | 375 | recursive | nothing | writeVertical(37); | 375 |
writeVerical(37) | 37 | recursive | nothing | writeVertical(3); | 37, 375 |
writeVerical(3) | 3 | stopping | 3 | 37, 375 | |
return from recursion | return | 7 | 375 | ||
return from recursion | return | 5 |
public static void f1(int n) {
System.out.println(n);
if (n > 1)
f1(n-1);
}
public static void f2(int n) {
if (n > 1)
f2(n-1);
System.out.println(n);
}
public static void f3(int n) {
System.out.println(n);
if (n > 1)
f3(n-1);
System.out.println(n);
}
public static void cheers(int n) {
if (n <= 1)
System.out.println("Hurrah");
else {
System.out.println("Hip");
cheers(n-1);
}
}
public static void cheers2(int n) {
if (n > 1) {
cheers2(n-1);
System.out.println("Hip");
} else {
System.out.println("Hurrah");
}
}
public static void cheers3(int n) {
if (n > 1) {
System.out.println("Hip");
cheers3(n-1);
System.out.println("Hip");
} else {
System.out.println("Hurrah");
}
}
public static void cheers4(int n, int max) {
if (n > max/2) {
System.out.println("Hip");
cheers4(n-1, max);
System.out.println("Hip");
} else {
System.out.println("Hurrah");
}
}
public static void recurse1(int n) {
System.out.println(n);
if (n>1)
recurse1(n-1);
System.out.println(n);
}
public static void starclamation(int n) {
System.out.println("*");
if (n>1)
starclamation(n-1);
System.out.println("!");
}