Using Recursion
Functions can call themselves in Objective-C, a process called recursion, and this process is often useful. For example, say you’re writing a function that calculates factorials: for example, 6! =6 x 5 x 4 x 3 x 2 x 1 = 720. Here’s a function that calls itself recursively to figure out factorials:
int factorial(int value) { if (value == 1) { return value; } else { return value * factorial(value - 1); } }
Let’s use this function to calculate 6!.
To use recursion:
- Create a new program named functionrecursion.m.
- In functionrecursion.m, enter the code shown in Listing 4.17.
This code calls the factorial() function, passing it a value of 6.
- Add the code to implement the recursive factorial() function (Listing 4.18).
- Save functionrecursion.m.
- Run the functionrecursion.m program.
You should see the following:
6! = 720
Listing 4.17. Starting functionrecursion.m.
#include <stdio.h> int main() { printf("6! = %i\n", factorial(6)); return 0; }
Listing 4.18. The functionrecursion.m program.
#include <stdio.h> int factorial(int value); int main() { printf("6! = %i\n", factorial(6)); return 0; } int factorial(int value) { if (value == 1) { return value; } else { return value * factorial(value - 1); } }
Listing 4.19. Starting functionpointers.m.
#include <stdio.h> void printem(void); void caller_function(void (*pointer_to_ function)(void)); int main() { caller_function(printem); return 0; } void printem(void) { printf("Hello there");; }