-
Recursive Function
I'm tring to write a recursive function that takes as a parameter a non-negative integer and generates the following pattern of stars if the integer is 4.
*
* *
* * *
* * * *
* * *
* *
*
Below is the code I have so far. Which gives me
*
* *
* * *
* * * *
Can anyone explain how to get the other half?
Code:
#include <iostream>
#include <iomanip>
#include<fstream>
using namespace std;
int func(int x);
int main(int argc, char *argv[])
{
int number;
func(4);
system("PAUSE");
return 0;
}
int func(int x)
{
int i;
if (x>=1)
func(x-1);
for (i=1; i<=x; i++)
{
cout<<"* ";
}
cout << endl;
return 1;
}
-
There are multiple ways to do this
You can add a second argument to the function that tells you whether it's growing or shrinking
or...
Check the value of x and if it's greater than 4, draw x - x%5 stars
-
I have added a second argument. I'm still getting the same result. I'm missing something somewhere. Just not sure where.
-
What am I missing?
Code:
#include <iostream>
#include <iomanip>
#include<fstream>
using namespace std;
int func(int x, int y);
int main(int argc, char *argv[])
{
int number;
func(4);
func(0);
system("PAUSE");
return 0;
}
int func(int x, int y)
{
int i, j;
if (x<=4)
func(x+1);
for (i=1; i>=x; i++)
{
cout<<"* ";
}
cout << endl;
if (y<=0)
func(y+1);
for (j=1; j>=y; j--)
{
cout<<"* ";
}
cout << endl;
return 1;
}
-
If the question is "what have I missed", I fear that the answer is "everything".
For any recursion, you'll have to decide what the base case is -- the simple thing to do, the part where the recursion stops. In your example, it would appear to be the case where the line we need to print is the long line; if so just print it and be done.
If we're not on the long line, we need to print out our short line, make a recursive call to print out the longer lines, and then print another short line at the bottom to make the pyramid shape.
-
How does a recursive function work?
Let me demonstrate an example:
Code:
Entering foo: 0
Entering foo: 1
Entering foo: 2
Entering foo: 3
Entering foo: 4
Entering foo: 5
Entering foo: 6
Entering foo: 7
Entering foo: 8
Entering foo: 9
Entering foo: 10
Leaving foo: 10
Leaving foo: 9
Leaving foo: 8
Leaving foo: 7
Leaving foo: 6
Leaving foo: 5
Leaving foo: 4
Leaving foo: 3
Leaving foo: 2
Leaving foo: 1
Leaving foo: 0
This is the output for some (secret) code. It shows the logic of recursive functions.
With this information, you should be able to write your stars.