how to use recursive functions in c++

Edited 4 Years Ago by adeel381

Do you want to know the mechanics of how to use a recursive function or under what conditions is it useful to use recursive functions?

Here is an example of a recursive function (the print_countdown function, ignore the rest), you can copy-paste it and try it out:

#include <iostream>
#include <iomanip>

#ifdef WIN32

#include <windows.h>

static std::size_t get_stack_size() {
  MEMORY_BASIC_INFORMATION mbi;
  VirtualQuery(&mbi, &mbi, sizeof(mbi));
  VirtualQuery(mbi.AllocationBase, &mbi, sizeof(mbi));
  VirtualQuery((char*)mbi.BaseAddress + mbi.RegionSize, &mbi, sizeof(mbi));
  VirtualQuery((char*)mbi.BaseAddress + mbi.RegionSize, &mbi, sizeof(mbi));
  return mbi.RegionSize;
}; 

#else

#include <pthread.h>

static std::size_t get_stack_size() {
  std::size_t stacksize;
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_getstacksize (&attr, &stacksize);
  return stacksize;
};

#endif

void print_countdown(int i) {
  int new_i = i - 1;
  std::cout << "\rCountdown to stack-overflow: " << std::setw(7) << new_i; std::cout.flush();
#ifdef WIN32
  Sleep(0);
#else
  usleep(0);
#endif
  print_countdown(new_i);
};


int main() {

  print_countdown(get_stack_size() / (8 * sizeof(std::size_t)));

  return 0;
};
  1. Find out base case
  2. Find out how you can solve case n with cases upto-not-including n
  3. Write the code
  4. Debug
  5. Deploy
  6. Train users
  7. Maintain
This article has been dead for over six months. Start a new discussion instead.