Write a recursive program to produce a pattern of n lines of dollar signs. The f
ID: 3546292 • Letter: W
Question
Write a recursive program to produce a pattern of n lines of dollar signs. The first line contains one dollar sign, the second contains 2, and so on up to the nth line, which contains n dollar signs. Line n+1 again contains n dollar signs, the next line has n - 1 dollar signs, and so on until line number 2n, which contains 1 dollar sign.
For example, if n is 4, the program would produce the following:
$
$$
$$$
$$$$
$$$$
$$$
$$
$
Hint: The easiest way to write this program is to write multiple recursive methods: one method would act like an outer loop, calling the other method(s) as well as itself; the "inner loop" methods would only call themselves.
Explanation / Answer
public class DollarPattern
{
public static void draw(int n, String pad)
{
if (n == 0)
return;
System.out.print(pad);
System.out.println("$");
draw(n-1, pad + "$");
System.out.print(pad);
System.out.println("$");
}
public static void pattern(int n)
{
draw(n, "");
}
public static void main(String[] args)
{
pattern(5);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.