Rectangle: Click to edit Master text styles
Second level
Third level
Fourth level
Fifth level
Recursion
An Example
wvoid doll(int size) {
w if(size==0)//No doll can be smaller than 1 atom                // (10^0==1) so doesn't call itself
w   return; //Return does not have to return            //something, it can be used to exit a function
w   doll(size-1); //Decrements the size variable so // the next doll will be smaller.
w}
wint main() {
w doll(10); //Starts off with a large doll (its a // logarithmic scale)
w return 0; //Finally, it will be used
w}
This program ends when size equals one. This is a good base case, but if it is not properly set up, it is possible to have an base case that is always true (or always false).

Once a function has called itself, it will be ready to go to the next line after the call. It can still perform operations. One function you could write could print out the numbers 123456789987654321. How can you use recursion to write a function to do this? Simply have it keep incrementing a variable passed in, and then output the variable...twice, once before the function recurses, and once after...