How can I write a RECURSIVE function in C that will take in a number, n, and will display one * on the first line, then one more each line until it displays a line with n *'s.
Example: draw(4) would display:
*
**
***
****
My main problem is getting it to print a new line at the appropriate time, and not after each *
C Programming?
One way would be with a static recursion counter (statics in functions have a single location and aren't part of the automatic variables created on each call of the function), incremented on each recursive call and decremented when each recursive call ends.
When the function ends with the count at zero, put out the \n.
Hope that helps.
Reply:Draw(4) implies Draw(3) and so on.
void draw(int n)
{
int i;
if(n %26lt; 1) return;
draw(n-1); /* recursive call */
for(int i=0;i%26lt;n;i++)
{
printf("*");
}
printf("\n");
}
Reply:This should work
void draw(int n)
{
if(n%26gt;1) draw(n-1);
for(int i=0;i%26lt;n;i++) printf("*");
printf("\n");
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment