Assume the availability of a method named printStars that can be passed a non-ne
ID: 3770188 • Letter: A
Question
Assume the availability of a method named printStars that can be passed a non-negative integer n and print a line of n 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 1asterisk, followed by a line of 2 asterisks, and then a line of 3 asterisks, and so on and finally a line of n asterisks. For example, if themethod 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
Here is the logic for you. If you need further refinement, just get back to me. Note that, you asked me not to use a loop in printTriangle() and not in printStars().
#include <iostream>
using namespace std;
void printStars(int n)
{
for(int i = 0; i < n; i++)
cout<<"* ";
}
void printTriangle(int n)
{
if(n != 0)
{
printTriangle(n-1);
printStars(n);
cout<<endl;
}
//else
//printTriangle(n-1);
}
int main()
{
printTriangle(5);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.