Fibonacci Nth term using tail recursion I have created a program that prints the Nth term of the Fibonacci sequence. The fib function needs to use tail recursion. If what I have coded isn't tail recursion, I would like to know how to change the fib function so it does.

#include &lt;iostream&gt;
#include &lt;sstream&gt;

int fib(int n, int i = 0, int a = 0, int b = 1)
{   
    return (i &gt;= n - 1) ? a : fib(n, i + 1, b, a + b);
}

int main(int argc, char* argv[])
{
    if (argc &lt; 2) {
        std::cerr &lt;&lt; "Argument 2 must be the Nth term." &lt;&lt; std::endl;
        return -1;
    }

    std::stringstream ss_obj(argv[1]);
    unsigned long int number;

    ss_obj &gt;&gt; number;

    std::cout &lt;&lt; "\nFibonacci number: " &lt;&lt; fib(number) &lt;&lt; std::endl;
    return 0;
}
To address your immediate concerns, it is a tail recursion indeed. OTOH, there is no need to be that terse. You may want to be a little more explicit:

    if (i == n) {
        return a;
    }
    return fib(n, i + 1, b, a + b);


Now the tail-recursiveness is obvious.



The error message "Argument 2 must be the Nth term." is misleading. The Nth term definitely refers to the Nth Fibonacci number, rather than the index of the number to be computed.

Besides that, traditionally such message is formatted as

    "Usage: " &lt;&lt; argv[0] &lt;&lt; " index\n";