Reputation: 65
I was trying to make recursive function that would simulate two for loops. So, function would have to do this:
int recursion(int n, int i, int j)
{
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
printf("%d %d\n", i, j);
}
}
}
but, i want it to be recursive. I tried something like:
int recursion(int n, int i, int j)
{
if(i<n)
{
if(j<n)
{
printf("%d %d\n", i, j);
recursion(n, i+1, j+1);
}
recursion(n, i+1, i+1+1);
}
}
I would call recursive one in main like
recursion(10, 0, 1);
but output is not the same for those two version of function. May anyone tell me where am I mistaking with the recursive one?
Upvotes: 1
Views: 3748
Reputation: 5457
recursion of two for
loops can be done this way:
void recursion(int n,int i,int j) //void since you return no value
{
if(i<n)
{
if(j<n)
{
printf("%d %d\n",i,j);
recursion(n,i,++j); //never use post increment
}
else
recursion(n,++i,0);
}
}
Sample input: (arguments are sent from main()
function)
5 1 1
Sample output:
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
2 4
3 0
3 1
3 2
3 3
3 4
4 0
4 1
4 2
4 3
4 4
Upvotes: 1
Reputation: 9385
For simulating nested for
loops, you should only increment one of your counter variables for each recursive call, depending on whether you're "in" the inner or outer loop. Also, the outer loop calls need to reset the inner loop counter to zero.
/* i for outer loop, j for inner loop, both going 0 to n-1 */
void recursion(int n, int i, int j)
{
if (i < n) {
if (j < n) {
// inner loop when j < n
printf("i=%d, j=%d\n",i,j); // inner loop body
recursion(n, i, j+1); // increment inner counter only!
} else { // when j has reached n...
// outer loop, which restarts inner loop
recursion(n, i+1, 0); // increment outer counter, reset inner
// since we're starting a new inner loop
}
}
}
If called initially as recursion(N, 0, 0)
this should be roughly equivalent to:
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("i=%d, j=%d\n", i, j);
}
}
...except that it doesn't account for modifications of i
within the inner loop (none happen in these examples, but if the inner loop did set i
larger than N
, the recursive version would break both loops without finishing the inner loop first).
Upvotes: 5
Reputation: 206697
I am not sure whether you can replace two for
loops with one recursive function. You can easily make it work with couple of recursive functions.
void recursion2(int n1, int n2)
{
if ( n2 >= 0 )
{
recursion2(n1, n2-1);
// Do whatever you need to do with the variables.
func(n1, n2);
}
}
void recursion1(int n1, int n2)
{
if ( n1 >= 0 )
{
recursion1(n1-1, n2);
recursion2(n1, n2);
}
}
Upvotes: 2