printing 2 triangles in a recursive function

hello
i need to print in recursion 2 triangles.. for example if num=3 then it will be:
***
**
*
*
**
***

i know how to do each triangle in recursive, my question is how to do the 2 triangles together in 1 recursive function..
in the code below i united the 2 triangles together in 1 function..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
using namespace std;

void printOpositeTriangles(int n);
void main()
{
	int n;
	cout << "please enter a number: " << endl;
	cin >> n;
	printOpositeTriangles(n);
}

void printOpositeTriangles(int n)
{
	int i, j;
	if (n == 0)

		return;
	
	else
	{
		for (i = 0; i < n; i++)
		{
			cout << "*";

		}
        cout << "\n";
		printOpositeTriangles(n - 1);
	}
	if (n == 0)
		return;
	else
	{
		printOpositeTriangles(n - 1);
		for (j = 0; j < n; j++)
		{
			cout << "*";
		}
		cout << "\n";
	}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <string>
#include <iostream>
using namespace std;

void print(unsigned n, unsigned max, bool descending)
{
    if (n == 1)
        descending = false;

    if (n <= max)
    {
        std::cout << std::string(n, '*') << '\n';
        print(descending ? n - 1 : n + 1, max, descending);
    }
}

void print(unsigned level) { if (level) print(level, level, true); }

int main()
{
    int n;
    cout << "please enter a number: " << endl;
    cin >> n;
    print(n);
}
Sorry but im studying c++ not c..
And its not bool.. Just the parameters i used.
Thanks for help anyway..
If someone else can help me to understand how to do the 2 triangles in recursion that would be good
cire did give you c++....
Also the solution you ask for cannot be done. There has to be more parameters.
I stand corrected. See cire's post below. I must confess I have been spending too much time learning tail recursive oriented programming languages such as ML. I like my accumulators. What can I say?
Last edited on
kevinkjt2000 wrote:
Also the solution you ask for cannot be done. There has to be more parameters.

More parameters are only required if the solution must be tail recursive, but I thought the OP could use a little more time to think on the solution. ;)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// http://ideone.com/blt5Rl
#include <iostream>
#include <string>
using namespace std;

void print(int n);

int main()
{
    int n;
    cout << "please enter a number: " << endl;
    cin >> n;
    print(n);
}

void print(int n)
{
    std::cout << std::string(n, '*') << '\n';

    if (n > 1)
    {
        print(n - 1);
        std::cout << std::string(n, '*') << '\n';
    }
}
Topic archived. No new replies allowed.