Recursion

The following was completed using JavaScript for CSC 324 at Georgetown College.

Intro

Have you ever heard of recursion? A recursive function is simply a function that runs itself. It requires a condition that enables it to stop running, otherwise it becomes an infinite loop (or it will just run forever).

The problem I had to solve, found in chapter three of Eloquent Javascript, was to create a function called isEven; isEven needs to take a single parameter (a positive, whole number) and check whether or not it is even.

The Solution

Here is my solution to the problem:

function isEven (x) {
    if (x == 1) {return false;} 
    else if (x == 0) {return true;}
    else if (x === undefined) {
      return "Please give a real number."}
    else {
      if (x < 0) {return isEven(x + 2)}
      else return isEven(x - 2);
    }
  }

The “if” statements simply check if a number is equal to either 1 or 0, and then outputs true or false. That is simple enough, but what if we were to run isEven with a number larger, or smaller, than 1 and 0?

if (x < 0) {return isEven(x + 2)}
      else return isEven(x - 2);

These statements, after the condition is found to be neither 1 or 0, check if x is either larger or smaller than those two numbers; and then x is returned and isEven is called again. Except, the numbers smaller than 0 are added 2 and the numbers larger than 1 are subtracted 2.

Eventually, whether the number is negative, positive, even or odd, we will get a result. The recursive function will be ran continuously, with x being modified, until a 0 or 1 is found.

The Output

Lets see this code work.

The following inputs, ran using the solution above, each have their outputs labeled with arrows below.

  console.log(isEven());
  // -> 'Please give a real number.'
  console.log(isEven(75));
  // -> false
  console.log(isEven(102));
  // -> true
  console.log(isEven(-14));
  // -> true
  console.log(isEven(-73));
  // -> false

We can see that non-numbers are granted with a request for a real number; and no matter how large or smal the number is, even numbers will be true and odd numbers will be false.