Recursion

Write your question here.
How do i define a recursive function printing a diamond


What do you want to use recursion for?

Recursion should be avoided as much as possible and only used when it makes sense because it is computationally expensive. For each function call you make there is so much additional overhead done that it just doesn't make sense to use it for such a trivial exercise.
Write your answer here.
the diamond needs polishing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

void recurse (int n, int p=1)
{
	for(int i=0; i<n-p; i++) cout<<" ";
	for(int i=0; i<2*p; i++) { cout << "*";	}
	cout <<endl;
	
	if(p<n)	recurse (n, p+1);
	
	for(int i=0; i<n-p; i++) cout<<" ";
	for(int i=0; i<2*p; i++) { cout << "*";	}
	cout <<endl;
}

int main()
{  
	recurse(5);     
}

@anup30
There is no instance of overloaded function recurse(int) being called in line 19
it is intended so, one of the arg has default value, so it runs.
the improvement it needs is polishing the diamond. and probably eliminating for loops.
sorry if didnt take not of int p= 1 of line 4
Topic archived. No new replies allowed.