Quantcast
Viewing latest article 2
Browse Latest Browse All 3

Answer by Lstor for Recursive a+b function

First of all, main should be declared int main.

Second, I would advise passing the cnt (which I have called iteration_number) as a parameter as well. Also, you should avoid using a global (b). If you define a helper function, that won't change the signature of your function:

int add_helper(int value, int max, int iteration_number){    if (iteration_number >= max) return value;    return add_helper(value + 1, max, iteration_number + 1);}int add(int a, int b){    add_helper(a, b, 0);}

Note that I have refactored your b to be a parameter, which I have called max. The function can be used like this:

int main(void){    int start = 9; // Your a    int count = 6; // Your b    int sum = succ(start, count);}

(If you are using C89 instead of C99 or C11, there should be a return 0; at the end of main()).


However, the "good" way to define addition recursively is by increasing one number and decreasing the other:

int add(int a, int b){    if (b == 0) return a;    return add(a + 1, b - 1);}

Modifying the function to work with negative numbers is left as an exercise to the reader.

(Note: Normally you want to subtract from the lowest number and add to the largest. I left that out to keep the example compact.)


I also want to understand how stacking happens in this case for variables cnt and x.

By "stacking", I assume you mean how the variables are pushed onto the stack as the function is called. Your cnt has static linkage, and is not pushed onto the stack at all. In my example, value, max and iteration_number will be pushed onto the stack for each call. (Exactly how is, as far as I know, implementation defined and depends on the calling convention in use.) In other words, assuming no optimization, the arguments will take iteration_number * sizeof(int) bytes on the stack.

If you want to keep track of the values, simply print them in the recursive function like this:

int succ_helper(int value, int max, int iteration_number){    if (iteration_number >= max) return value;    printf("%d: %d - %d\n", iteration_number, value, max);    return succ_helper(value + 1, max, iteration_number + 1);}

Can anyone suggest optimization or better code for this?

int sum = 9 + 6;

:-)


Viewing latest article 2
Browse Latest Browse All 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>