What is Recursion?

The simple answer is, it’s when a function calls itself.

Recursion function calling itself again and again.

But how does this happen? Why would that happen, and what are its uses?

When we talk about recursion, we are really talking about creating a loop. Let’s start by looking at a basic loop.

1
2
3
for(int i=0; i<10; i++) {
cout << "The number is: " << i << endl;
}
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
void numberFunction(int i) {
cout << "The number is: " << i << endl;
}
int main() {for(int i=0; i<10; i++) {
numberFunction(i);
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;
void numberFunction(int i) {
cout << "The number is: " << i << endl;
i++;
if(i<10) {
numberFunction(i);
}
}
int main() {int i = 0;
numberFunction(i);
return 0;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store