Publishers of technology books, eBooks, and videos for creative people

Home > Articles

This chapter is from the book

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:

  1. Create a new program named functionrecursion.m.
  2. In functionrecursion.m, enter the code shown in Listing 4.17.

    This code calls the factorial() function, passing it a value of 6.

  3. Add the code to implement the recursive factorial() function (Listing 4.18).
  4. Save functionrecursion.m.
  5. 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");;
}

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.