I'm new to recursion and am wondering how the output of the code below is 6. So from what I can understand, there are 2 base/anchor cases which return 0 or 1? Is this correct? And the recursive/inductive case is the f() calling f(), but I'm confused on what it returns. What is the +2 do to what the function returns? Im confused on that part mainly.

#include<iostream>
#include<string>
using namespace std;

int f(char ch1, char ch2)
{
     if(ch1>ch2)
        return 0;
     if(ch1+1==ch2)
        return 1;
     else
        return f(ch1+1,ch2-1) + 2;
}

int main()
{
    cout << f('a', 'e')<< endl;
    
    
    system("pause");
    return 0;
}

Basically, the function returns the difference between the lower number and the higher number, if and only if the lower number is the first number. The 2 is to account for the fact that both the lower number is being incremented and the higher decremented when they are passed to the recursive call.

Oh, thanks. A light just flipped on for me and I figured it out. that second 'if' statement would never be used in this case.

This question has already been answered. Start a new discussion instead.