![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Dec 2005
Posts: 18
Rep Power: 0
![]() |
void printStar(int input)
{
if (input >=0 )
{
printStar(input-1);
for(int i=1; i<=input; i++)
{
cout <<"*";
}
cout<<endl;
}
}i try to print the stars below with recursion, but i failed * ** *** *** ** * i would appreciate, if i got hint from u all |
|
|
|
|
|
#2 |
|
Newbie
Join Date: Apr 2006
Posts: 14
Rep Power: 0
![]() |
Do you see this line:
void printStar(int input)
{
if (input >=0 )
{
printStar(input-1);
for(int i=1; i<=input; i++)
{
cout <<"*";
}
cout<<endl;
}
}You keep recalling the function which makes it impossible to begin the for loop. You would probably want to do something like this.. void printStar(int input)
{
if (input >=0 )
{
for(int i=1; i<=input; i++)
{
cout <<"*";
}
printStar(input-1);
cout<<endl;
}
}Edit: Wait, did you want to print this: * ** *** *** ** * If so, you're going to have to do some more stuff. |
|
|
|
|
|
#3 |
|
Hobbyist Programmer
Join Date: Mar 2006
Location: Lebanon
Posts: 148
Rep Power: 3
![]() |
must disagree with you there, the code correction you posted is incorrect, this is not how recursion is done. in regards to the problem, the approach is correct, you have called the function recursively till you reach 0 then print line by line form 1 start up to 'input' stars .. this only gives half the figure unfortunately, i cant think of a a way to do it recursively. but if you want the end product to be
* ** *** *** ** * then just do a for-loop for the bottom part in main for (int i = input ; i >=1 ; i--) |
|
|
|
|
|
#4 | |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
void printStar(int count, int limit)
{
for (int i = 0; i < limit-count; i++) cout << '*';
cout << endl;
if (count ) printStar (count-1, limit);
for (int i = 0; i < limit-count; i++) cout << '*';
cout << endl;
}
int main (int argc, char *argv [])
{
printStar (5, 5);
puts ("Press ENTER to terminate\n");
getchar ();
return 0;
}Quote:
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
|
|
#5 |
|
Newbie
Join Date: Dec 2005
Posts: 18
Rep Power: 0
![]() |
thanks u all guys, i got a clue from dawei
thanks a lot ^^ |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|