does anybody know of a good source of really simple lessons about recursion? i'm trying to wrap my head around it, and a supply of easy examples would appreciated.
Recursion solves part of a problem each "iteration". It requires a base case, when to stop. The partial solutions can be assembled as the recursion "unwinds". Here's a simple, recursive function to convert a decimal (base 10) integer to any base between 2 and 35: characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" def mkDigit( number, base ): if( number == 0 ): return "" index = number % base number = number // base return mkDigit( number, base ) + characters[ index ]
Another Example: This prints numbers from 10 to 0 n=10 printNumber(n) { while(n<0) { //Print the Number print n; //Decrement the value by 1 n=n-1; //Calling the Recursive function printNumber(n); } }
Join our real-time social learning platform and learn together with your friends!