Recursive function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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 }

25th May 2019, 1:45 AM
Paolo Torregroza
Paolo Torregroza - avatar
4 Answers
+ 6
Recursive means repeatation .. the function called again and again untill condition fails ex:factorial program
25th May 2019, 9:37 AM
M.MANIVANNAN
M.MANIVANNAN - avatar
+ 5
This problem could have been done iteratively as well. There are many ways to skin a cat.
31st May 2019, 11:53 PM
Sonic
Sonic - avatar
+ 3
25th May 2019, 3:24 AM
Paolo Torregroza
Paolo Torregroza - avatar
+ 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.
25th May 2019, 7:53 PM
AZTECCO
AZTECCO - avatar