1

How I can pass this function of iterative to recursive

void triangulo(int max)
    {
        int i, j;
        for(i = 1; i <= max; i++)
        {
            for(j = 0; j < i; j++)
                printf("%d", j + 1);
            printf("\n");
        }
    }

Anyone has any idea? or it is impossible to do this?

update

void triangulo(int n, int i, int j)
{
    if(i <= n)
    {
        if(j < i)
        {
            printf("%d", j + 1);
            triangulo(n, i, j + 1);
        }
        if (j == i)
        {
            printf("\n");
            triangulo(n, i + 1, 0);
        }
    }
}
cheroky
  • 755
  • 1
  • 8
  • 16

2 Answers2

1

Try this : Here I make i and j as arguments because in each recursion they have different values.

void triangulo(int max,int i,int j) //make i and j as arguments
{
    if(i<max)
    {
        if(j<max)
        {
            printf("%d",j);
            triangulo(max, i, ++j);//dont use post increment operation
        }
        else
        {
            printf("\n");
            triangulo(max , ++i, 0);
        }
    }
}

Generally,

  • use if and else for condition and
  • send arguments at the end of it as what may happen in iterative method.
Cherubim
  • 5,287
  • 3
  • 20
  • 37