DEV Community

Kauress
Kauress

Posted on

2

The "I *dislike* recursion" notes

Writing these notes while I cringe and procrastinate. Yes, recursion is useful, so is my pet cat. Covers the general concept of recursion.

Definition

A recursive function, is a function that calls itself till a certain condition is met. A break criteria is necessary so that the function does not call itself infinitely.

So you can express operations in terms of itself.

A simple example is:

#include <iostream>

using namespace std;

void recurse (int count) // Each call gets its own count
{
  cout<< count <<"\n";

  recurse ( count + 1 );
}

int main()
{
  recurse ( 1 ); //First function call, so it starts at one        
}


Enter fullscreen mode Exit fullscreen mode

2 parts of a recursive function

  1. Base case (the condition that stops the recursion process)
  2. Recalling condition (the condition that causes the function to call itself)

Example

The classic example is calculating the factorial of a number.

#include <iostream>
using namespace std;
//Factorial function
int f(int n){
   /* This is called the base condition, it is
    * very important to specify the base condition
    * in recursion, otherwise your program will throw
    * stack overflow error.
    */
   if (n <= 1)
        return 1;
   else
       return n*f(n-1);
}
int main(){
   int num;
   cout<<"Enter a number: ";
   cin>>num;
   cout<<"Factorial of entered number: "<<f(num);
   return 0;
}


Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up