Quantcast
Channel: Recursive a+b function - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 3

Answer by Guffa for Recursive a+b function

$
0
0

"I also want to understand how stacking happens in this case for variables cnt and x. Are they stacking in pairs like 0-9, 1-10 ,2-11,3-12 ,4-13"

No, the value from cnt is not on the stack at all. It's global, so it will change along with the recursive execution.

"then at last when cnt is 5 it return x from the post-increment return?"

Well, yes it will return the value of x, but the post-increment is pointless as the variable is never used with the incremented value.

By using global variables in the recursive code, it's not using recursion properly. It still works as long as you only have a single branch of recursion, but for a more complex task the branches would mess with each others values.

To use recursion properly, you need to send all the data into the function that it needs:

void main(void) {  int a = 9, sum, b = 6;  sum = succ(a, b, 0);  printf("Sum returned : %d\n",sum);}int succ(int x, int y, int cnt) {  return cnt < y ? succ(x + 1, y, cnt + 1) : x;}

However, this is not really a good example of how recursion works. Normally a recursive function would divide the work into smaller parts that would each be executed recursively, instead of shaving off a single piece of work and do the rest of the work recursively. A recursive algorithm shouldn't go deeper than perhaps 10 or 20 levels. When you use recursion to just do looping, as in the example, it's inefficient and you will easily run into a stack overflow for larger values.


Viewing all articles
Browse latest Browse all 3

Trending Articles



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