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() {
  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;


#include <pthread.h>

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


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

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.