Rabu, 21 Oktober 2015

Recursion - C++

Recursion on C++??

I'm lacking the information on this matter so let's see what other site saying about Recursion:

"What is recursion? The simple answer is, it’s when a function calls itself."

And you might want to read this article about Array first:


Due to my very limited understanding about Recursion, it might be better if we just take a look at this:

Now with recursion, we won’t need to use a ‘for loop’ because we will set it up so that our function calls itself. Let’s recreate this same program one more time, only this time we will do it without a ‘for loop’. We will use a recursion loop instead, like this.

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;
}


We did it! We used recursion! You can see the call to ‘numberFunction’ is made only once in the main part of the program but it keeps getting called again and again from within the function itself, for as long as ‘i’ is less than 10.

Tidak ada komentar:

Posting Komentar