|
-
April 24th, 2003, 11:00 PM
#1
need some recursion help
first off, YES THIS IS HOMEWORK so anyone put off by that can stop reading right now.....
i'm supposed to write a recursive function that will take 2 numbers and print out a series of * based on those....basically what it boils down to is something like
triangle(cout, 3, 5);
would display
***
****
*****
****
***
i can get up to that third line there but the going back down part is confusing me and i would greatly appreciate any help.
here's what i have so far.....
Code:
void triangle(ostream& outs, int m, int n){
int i;
for(i=0;i<m;i++)
outs << "*";
cout << endl;
if(m != n)
{
triangle(outs, m+1, n);
}
}
-
April 24th, 2003, 11:21 PM
#2
You're so close though!
Just glancing quickly (unless I'm cracked), can you not just repeat the printing code after the recursive call to triangle? Then, it'll print them on the way up the recursion tree, then again on the way back down, too!
HTH,
Bassman
-
April 24th, 2003, 11:26 PM
#3
the problem there would be the conditional. counting back down with another call like
triangle(outs, n-1, m); prints the right number of lines but they dont have the right amount of characters. i cant call the function again from OUTSIDE it, it's supposed to be done completely recursively which this going back down part i'm drawing a blank on. (funny how i can figure out stuff that should be lots harder but this is driving me mad).
simply adding another call inside the function itself is causing all kinds of infinite recursions
-
April 24th, 2003, 11:43 PM
#4
No, I meant just the printing code - like this:
Code:
void triangle(ostream& outs, int m, int n){
int i;
for(i=0;i<m;i++)
outs << "*";
cout << endl;
if(m != n)
{
triangle(outs, m+1, n);
/// NEW STUFF!!!
for(i=0;i<m;i++)
outs << "*";
cout << endl;
}
}
Works for me!
Cheers,
Bassman
-
April 24th, 2003, 11:46 PM
#5
you're exactly right, wow. yeah when that nested call returns it has the same value of m that then needs to be displayed again.
seems so obvious after the fact.....thank you good sir, much appreciated.
-
April 25th, 2003, 08:14 AM
#6
Re: need some recursion help
Originally posted by filthy_mcnasty
first off, YES THIS IS HOMEWORK so anyone put off by that can stop reading right now.....
Homework questions are welcomed here. What is not welcomed here is someone posting the homework requirements with no code as to what they've done.
Regards,
Paul McKenzie
-
April 25th, 2003, 01:37 PM
#7
yeah i know paul. i have noticed, however, that some people react adversly to anything that seems like homework so i just thought i'd give them a warning.
at any rate, will you do the rest of my homework for me now?
=)
just kidding, thanks again.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|