Click here to Skip to main content
15,886,666 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
#include <iostream>
#include <iomanip>
using namespace std;

int fn(int a) {
	cout << a << "-";
	if ((a == 0) || (a == 1))
		return a;
	return fn(a - 1) + fn(a - 2);
}

int main() {
	int a = fn(4);
	cout << a << endl;
	return 0;
}


What are the steps for solving this question?
Posted
Updated 14-Dec-15 0:05am
v2

1) Open Visual studio.
2) Copy and paste the code into a new project.
3) Run the application.

Alternatively, walk through the code and work out what happens each time you execute a line based on the values the line started with.

This is your homework, not ours: so it's up to you to do this, not us.
 
Share this answer
 
You have to use yourself as a debugger.
Let's make together just the first steps, starting from main, of course, we have:
C++
int a = fn(4);

In order to assign the correct value to a we have to evaluate fn(4).

So, let's step into fn(4):
  • We can safely ignore the cout line.
  • The if condition evaluates to false, since 4 is neither 0 nor 1.
  • Eventually we reach the line
    return fn(3) + fn(2);

    This tell us we have to step again (and again) into fn, with different argument values, in order to know our final result.


I suppose it is enough to make you figure out how to complete the homework.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900