Assume the availability of a method named makeStars that can be passed a non-neg
ID: 3653909 • Letter: A
Question
Assume the availability of a method named makeStars that can be passed a non-negative integer n and print a line of asterisks. Write a method named printTriangle that receives a non-negative integer n and prints a triangle of asterisks as follows: first a line of n asterisks, followed by a line of n-1 asterisks, and then a line of n-2 asterisks, and so on. For example, if the method received 5 it would print: * * * * * * * * * * * * * * * The method must not use a loop of any kind (for, while, do-while) to accomplish its job. The method should invoke printStars to accomplish the task of printing a single line.Explanation / Answer
The basics of any recursion is to be able to write an expression with what you want on the left as a function of previous values:
f(n) = F( f(n-1) );
and
a stop condition, which for you is
n==0
Although I shouldn't do it (because just getting the answer here lessens the learning experience) the first recursion is easy:
int sum( int[] arr, int len ) {
...if( len == 0 ) return 0;
...return arr[len-1] + sum( arr, len-1 );
}
+add
Corrected an error.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.