Course Content
Programming in C
About Lesson

Recursion refers to the ability of a function to call itself. When a function calls itself recursively, each invocation gets a fresh set of all the automatic variables, independent of the previous set. Let’s look at the following code for binary search:

int bin_search(int arr[], int num, int low, int high)
{
  if (low > high)
    return -1; 
  int mid = low + (high - low) / 2;
  if (num == arr[mid])
    return mid;
  if (num < arr[mid])
    return bin_search(arr, num, low, mid - 1); 
  return bin_search(arr, num, mid + 1, high);
}

Here, we reduce the search space and call the function again until either we find the number or exhaust the list.

Recursion provides no saving in storage, since the state of the recursive calls need to be saved in the call stack. Not will it be faster. But recursive code is often compact and much easier to understand than the non-recursive equivalent.

Scroll to Top