Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does recursion work in C?

Tags:

c

recursion

I'm trying to understand how recursion works in C. Can anyone give me an explanation of the control flow?

#include <stdio.h>
/* printd: print n in decimal */
void printd(int n)
{
  if (n < 0)
  {
    putchar('-');
    n = -n;
  }
  if (n / 10) printd(n / 10);
  putchar(n % 10 + '0');
}

int main()
{
  printd(123);
  return 0;
}
like image 545
foo Avatar asked Mar 16 '26 20:03

foo


1 Answers

The control flow looks like this (where -> is a function call)

main()
 └─> printd(123)
      ├─> printd(12)
      │    ├─> printd(1)
      │    │    └─> putchar('1')
      │    └─> putchar('2')
      └─> putchar('3')
like image 71
caf Avatar answered Mar 19 '26 13:03

caf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!