0

I recently started learning about tail and head recursion and there are a couple of questions I'd like to ask.

  1. In the tailRec function below, the program prints a new line when tailRec(0), the stopping condition, is called instead of just doing nothing. Does this count as tail recursion?
#include <iostream>

void tailRec(int n)
{
    if (n) 
    {
        std::cout << n << " ";
        tailRec(n-1);
    }
    else std::cout << std::endl; // Adding this doesn't make it count as tail recursion anymore?
}

What if I put the print new line statement at the beginning of the function, before the if statement?

  1. I have a similar question for the headRec function below as well.
void headRec(int n)
{
    
    if (n)
    {
        headRec(n-1);
        std::cout << n << " ";
    }
    else std::cout << std::endl; // Adding this doesn't make it count as head recursion anymore?
}

I tried looking online but I couldn't find a sufficient answer to my question.

Faizaan A.
  • 19
  • 3

0 Answers0