c++ - Need to know why the code behaves in this way - explanation code in C -


#include <stdio.h>  int main() {     int c;      c = f(3, 5);     printf("c = %d\n", c);         c = f(4, 2);     printf("c = %d\n", c);         c = f(2, 4);     printf("c = %d\n", c);         c = f(3, 3);     printf("c = %d\n", c); }  int f(int d, int e) {     if (e > 0)         return f(d, e - 1) + f(d, e - 1);     else         return d;     } 

i know code gives me product between d (the first number in f) , 2 elevated second number in f(function)

the problem don't understand why gives me such output, don't see operators within code (something equation d*2^e). deep explanation appreciated, feel free recommend material can helpful in learning c.

this simple recursive function, can write in such way:

         |  f(d, e-1) + f(d, e-1)   if e > 0 f(d,e) = |          |  d                       otherwise 

but can add 2 equal terms f(d,e-1), , becomes:

         |  2* f(d, e-1)    if e > 0 f(d,e) = |          |  d               otherwise 

in order let understand, try expand function. following rule, can write:

f(d,0) = d    d  // identify function 

that because definition, since e=0.

going ahead:

f(d, 1) = 2*f(d, 0) =           2*d  f(d, 2) = 2*f(d, 1) = 2*(2*d) = 4*d  f(d, 3) = 2*f(d, 2) = 2*(4*d) = 8*d  ...  // inductivly... f(d, k) =  2^k *d     // k > 0 

Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -