+ 4
Recursive function
Hi, I don't understand pefectly how this c++ code world, i know that it serves to make a power and that for example 2^4 = 2*2^3 and so on, what I don't understand is the flow and the behavior of c++ int power (int num, int pow){ if (pow == 0){ return 1; } else{ return num * power(num, pow-1); } } int main(){ cout<<power(2,4); //16 return 0 }
4 odpowiedzi
+ 6
Recursive means repeatation .. the function called again and again untill condition fails ex:factorial program
+ 5
This problem could have been done iteratively as well. There are many ways to skin a cat.
+ 3
Thanks Jay Matthews
+ 2
Recursion is the technique to make a function call itself, we also have to define a condition to exit from this loop, if not it will call itself recursively infinite times .
In your example "if pow==0 return;" is the exit for that loop.
Recursion is not really recommended due to low readability and issues.
In normal programming you should use loops, use recursion only if needed.
It is used in Template Meta Programming because it is the only way to build loops making TMP Turing complete.