C++ Tutorial: Recursion

preview_player
Показать описание

Recursion can be simply thought of as another form of repetition, albeit a less efficient one. Why not just use a loop then? Well, some problems find a natural expression of their solution in the form of a recursive function. In other words, it's easier.

In this video, I write two functions: one iterative, and one recursive. The sample functions count down from some integer argument to 1 and then announces Blastoff! One uses a while loop and the other uses a call to itself.

I explain what a base case is and what a recursive function call is. Additionally, I demonstrate the basic template for a recursive function and discuss how to avoid infinite recursion.

I compare a loop-based repetitive function to a function that achieves repetition by calling itself.
Рекомендации по теме
Комментарии
Автор

this tumb nail is getting me excited to wrte some code

pspsora
Автор

Hi!
In this case (i put the cout<<n<<endl; under the function call) the output will be:
1
2
3
4
5

Why is this happening?


# include<iostream>
using namespace std;

/*program for recursive function

*/
void fun(int n)
{
if(n>0)
{

fun(n-1);
cout<<n<<endl;
}
}
int main()
{
int x=5;
fun(x);
return 0;
}

andreicionca