Java Reference
In-Depth Information
Answers to Self-Test Exercises
1.
Hip Hip Hurray
2.
public static void
stars(
int
n)
{
System.out.print('*');
if
(n > 1)
stars(n
−
1);
}
The following is also correct, but is more complicated:
3.
public static void
stars(
int
n)
{
if
(n <= 1)
{
System.out.print('*');
}
else
{
stars(n
−
1);
System.out.print('*');
}
}
public static void
backward(
int
n)
{
if
(n < 10)
{
System.out.print(n);
}
else
{
System.out.print(n%10);
//write last digit
backward(n/10);
//write the other digits backward
}
}
4.
public static void
writeUp(
int
n)
{
if
(n >= 1)
{
writeUp(n
−
1);
System.out.print(n + " ");
//write while the
//recursion unwinds
}
}