Mastery 21

Use of recursion for repetitives algorithms

What is recursion? The simple answer is, it’s when a function calls itself. But how does this happen? Why would this 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.

 



For those who don’t yet know, this basic loop displays the sentence, “The number is: ” followed by the value of ‘i’. Like this.


Inside the ‘for loop’ declaration we have the integer variable ‘i’ and have its starting value of 0. So the first time the sentence is displayed it reads, “The number is: 0”. The part of the ‘for loop’ declaration that is ‘i++’ tells the program that each time the loop repeats, the value of ‘i’ should be increased by 1. So, the next time the sentence is displayed it reads, “The number is: 1”.
This cycle will continue to repeat for as long as the value of ‘i’ is less than 10. The last sentence displayed would read, “The number is: 9”. As you can see the basic ‘for loop’ has three parts to its declaration, a starting value, what must remain true in order to continue repeating, and a modifying expression. Everything that is contained within the {braces} is what the program performs. Cout stands for console out, and prints words or characters to the screen.
So what does this have to do with recursion? Remember recursion is a loop. What if I did not want to just print a message to the screen? A loop can be used to perform other tasks as well.

Credit:

http://www.cplusplus.com/articles/D2N36Up4/

1017 21

CC BY 4.0 Mastery 21 by Mauricio Cooper is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.