Home > Enterprise >  Not understanding a recursive function in C
Not understanding a recursive function in C

Time:10-30

#include <stdio.h>

void PrintNumPattern(int x, int y)
{
  if (x > 0) 
  {
        printf("%d ", x);
        PrintNumPattern(x - y, y);
        printf("%d ", x);//idk why this makes it work...why does it add?
    } else {
       printf("%d ", x); 
    }
 
} 

int main(void) {
   int num1;
   int num2;
   
   scanf("%d", &num1);
   scanf("%d", &num2);
   PrintNumPattern(num1, num2);
}

So currently I am learning about recursion and how it works. The code above is supposed to get an input, for example, "12 3" and then output "12 9 6 3 0 3 6 9 12" but so far I am so confused. Why does the printf,that I put a comment on, start adding after 0? The program only gets told to subtract not add. Also how does the program know to stop at 12?

CodePudding user response:

start adding after 0?

It never adds anything. It's just that there are two printf calls in the first condition that print the same number - once before the recursive call and once after it.

Also how does the program know to stop at 12

The recursive call stops at 0. Then it returns to the parent call which will print it's number.

It will help if you write out the call tree. I've tried to visualise it as shown below. Each indent represents a function call from a parent function. On the right hand column I show the resulting output.

PrintNumPattern(12, 3)
    printf(12) -------------------------> 12
    PrintNumPattern(9, 3)
        printf(9) ----------------------> 9
        PrintNumPattern(6, 3)
            printf(6) ------------------> 6
            PrintNumPattern(3, 3)
                printf(3) --------------> 3
                PrintNumPattern(0, 3)
                    printf(0) ----------> 0
                printf(3) --------------> 3
            printf(6) ------------------> 6
        printf(9) ----------------------> 9
    printf(12) -------------------------> 12

Another way to look at it which may (or may not) be helpful is to visualise just one level of the recursive call. This clearly shows that there is no "addition" but only a repetition.

PrintNumPattern(12, 3)
    printf(12) -------------------------> 12
    PrintNumPattern(9, 3) --------------> 9 6 3 0 3 6 9
    printf(12) -------------------------> 12

CodePudding user response:

The reason the second printf was necessary is that you want to repeat what you printed on the way down to 0. It may look like you're adding but all you're doing is repeating your printf calls in reverse. Visualizations either by hand or tool can help build an intuition for recursive functions. See this example for a visualization of PrintNumPattern(2, 1)

  • Related