Can anyone solve and explain this for me? It\'s a C++ Data Structures and Algori
ID: 3853429 • Letter: C
Question
Can anyone solve and explain this for me?
It's a C++ Data Structures and Algorithms course, topic is about Recursion
Question 3: Little Johnny likes recursion. Every year his grandpa asks him "How old are you now Little Johnny?" and he replies "One year older than last year." (a) Write a simple (non-tail) recursive function that takes the current year as argument and return Little Johnny's age, calculated as per the rule above. Assume Little Johnny is born in 2009. Code error cases too. (3 marks) int Age( int year)( (b) Modify the above age function to be tail recursive. (3 marks) int Age( int year,Explanation / Answer
The non-tail recursive function :
#include <iostream>
using namespace std;
int Age( int Year) {
int currentAge = 1;
if ( Year < 2009) {
cout << "Jhonny is not yet born " << endl;
return 0;
}
else if ( Year == 2009 )
return 1;
currentAge = 1 + Age(Year - 1);
return currentAge;
}
int main()
{
cout << Age(2015) <<endl;
return 0;
}
2) Tail recursive function :
#include <iostream>
using namespace std;
int Age( int Year) {
if ( Year < 2009) {
cout << "Jhonny is not yet born " << endl;
return 0;
}
else if ( Year == 2009 )
return 1;
return 1+ Age( Year - 1 );
}
int main()
{
cout << Age(2015) <<endl;
return 0;
}