Two loops into Recursive
Feb 6, 2019 at 4:59am UTC
Hello,
I was trying to convert these nested loops into a recursion form, this is my first time and i need assistance.
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
for (i = 0; i < 2 * n ; i++)
for (j = 0; j < n; j++)
counter++;
// into recursion.
void TwoLoopS(int &count , int n, int i, int j)
{
if (i < 2 * n)
{
count++;
TwoLoopS(count, 2 * n, i++, j);
if (j < n)
{
count++;
TwoLoopS(count, n - 1, i, j++);
}
}
else
{
return ;
}
}
Feb 6, 2019 at 5:06am UTC
Something like
1 2 3 4 5 6 7 8 9 10
if ( i < 2*n ) {
if ( j < n ) {
count++;
j++;
} else {
j = 0;
i++;
}
// recurse
}
Feb 6, 2019 at 5:43am UTC
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
#include <iostream>
#include <iomanip>
int loop( int counter, int j )
{
if ( j <= 0 ) return counter ;
else return loop( counter+1, j-1 ) ;
}
int outer_loop( int counter, int n, int i )
{
if ( i <= 0 ) return counter ;
else return outer_loop( loop( counter, n ), n, i-1 ) ;
}
int main()
{
for ( int n = 0 ; n < 15 ; ++n )
{
std::cout << std::setw(2) << n << " : " ;
int counter = 1000 ;
std::cout << counter + 2*n*n << ' '
<< loop( counter, 2*n*n ) << ' '
<< outer_loop( counter, n*2, n ) << ' ' ;
for ( int i = 0; i < 2*n ; ++i )
for ( int j = 0; j < n ; ++j ) ++counter ;
std::cout << counter << '\n' ;
}
}
http://coliru.stacked-crooked.com/a/b5cf1c09604f5576
Topic archived. No new replies allowed.