Pointers in C with recursion -
i programme in java , watching c codes. came across programme , don't know how pointer thing working. know pointer stores address , couldn't create through program. please tell how output coming 8 ?
#include <stdio.h> int fun(int n, int * f_p) { int t, f; if (n <= 1) { *f_p = 1; homecoming 1; } t = fun(n - 1, f_p); f = t + *f_p; *f_p = t; homecoming f; } int main() { int x = 15; printf("%d\n", fun(5, &x)); homecoming 0; }
what have here recursive function calculates i-th element of fibonacci sequence (indexing 0
). each recursive iteration returns 2 values: i-th fibonacci number , (i-1)-th (previous) fibonacci number. since function in c can homecoming 1 value (well, unless utilize struct homecoming type), other value - previous fibonacci number - returned caller through pointer parameter f_p
.
so, when phone call fun(5, &x)
, function homecoming 8
, 5-th fibonacci number, , place 5
x
, previous (4-th) fibonacci number.
note initial value of x
not matter. 15
not play role in program. apparently there reddish herring.
if know fibonacci sequence is, know next element of sequence sum of 2 previous elements. why function written "return" 2 elements of sequence caller. might not care previous value in top-level caller (i.e in main
), nested recursive calls need calculate next number. rest pretty straightforward.
c pointers recursion
No comments:
Post a Comment