I used the debugger to examine this code but not understanding a couple areas.

  1. Why does the for loop repeat after it exits to print a new line? If it exits the loop, shouldn’t it be done with it?
  2. Why is n incremented and not i as stated with i++?

int main(void)
{
    int height = get_int("Height: ");

    draw(height);
}

void draw(int n)
{
    if (n <= 0)
    {
        return;
    }

    draw(n - 1);

    for (int i = 0; i < n; i++)
    {
        printf("#");
    }
    printf("\n");
}
  • milon@lemm.eeOP
    link
    fedilink
    arrow-up
    2
    ·
    9 months ago

    Why does the for loop return when it hits the end of the function? Isn’t the recursive portion already completed in draw(n - 1)? The rest of it is just normal non-recursive code if I understand it correctly.

    • Mac@programming.dev
      link
      fedilink
      arrow-up
      5
      ·
      edit-2
      9 months ago

      When the draw function calls itself it yields control to that new function its calling. When that function ends it takes back control and continues doing what it was doing.

      This means all of the for loops in all of the functions will execute. Draw(1) will do the for loop and then return as it hits the end of the function (standard behaviour when you reach the end of a function even if theres no return statement). Then draw(2) will do the for loop as it gets back control now that draw(1) is done and then return, etc. all the way up

      All parts of a function are recursive, theres no such thing as a non recursive part

    • supernicepojo@lemmy.world
      link
      fedilink
      arrow-up
      2
      ·
      9 months ago

      This is all a really great example of how The Stack works. As the loop recurses it continually adds to the program stack in memory and then plays the next “item” in the stack. There is a specific limit to recursion as well based on this principle.