Quick Note on Recursion

Recursion

Example in PHP using the factorial:

  1. // $n must be a positive integer or 0 - function returns 1 for 0 and all errors
  2. function factorial($n)
  3. {
  4.   if ($n > 0 && is_int($n))
  5.   {
  6.     // factorial of positive integer
  7.     return $n * factorial($n - 1);
  8.   } else
  9.   {
  10.     // factorial of 0
  11.     return 1;
  12.   }
  13. }

There are many other blog posts that cover this topic well. Some include:

Recursion in PHP (and iteration)

Recursive patterns in Regex from the PHP manual

Here is a little snippet of a C++ function that will ask for user input and make sure it is a float. If it’s not a float, the functions recurses (is that a word?)… calls itself. The end effect is that the user is asked to enter a float until they do. You must include both iostream and limits.

  1. float collectFloat()
  2. {
  3.   float user_input(0.0);
  4.   try
  5.   {
  6.     // Could also use cin.fail() to check for success
  7.     if (cin >> user_input) cinIgnoreRest();
  8.     else
  9.       throw (string(ā€œ\nNot a float entered.\n Please enter a number.\nā€));
  10.   }
  11.   catch (string error)
  12.   {
  13.     cout << error << ā€œ==> ā€œ;
  14.     cin.clear();
  15.     cinIgnoreRest();
  16.     // This will keep repeating until user enters a float
  17.     user_input = collectFloat();
  18.   }
  19.     return user_input;
  20. }

Tags: ,

One Response to “Quick Note on Recursion”

Leave a Reply

blog