Hi, I have this factorial function that I have working just great, but I am not really sure how I am supposed to print the local variable and the recursive call parameter. Any help would be greatly appreciated! Thanks.

#include <iostream>
using std::cout;
using std::endl;

#include<iomanip>
using std::setw;

unsigned long factorial(unsigned long);

int main()
{
	for (int counter = 0; counter <= 10; counter++)
		cout<< setw(2) << counter <<" ! = "<<factorial(counter)<<endl;
	
return 0;
}

unsigned long factorial(unsigned long number)
{
	if (number <= 1)
		return 1; 
	else
		return number * factorial(number - 1);
	cout<<number<<endl;
}

What's the difference between the local variable and the recursive call parameter?

Your cout<<number<<endl; never gets to run because you are always returning before it gets a chance.

Thats what I am not really sure about. I am not sure what is being asked for. The cout<<number<<endl; should not have been in the code.

Well it's a bit difficult to give an answer to an unknown question.

Here's my suggestion.

unsigned long factorial(unsigned long number)
{
   unsigned long retVal;
   
   cout<<"Call to factorial(" << number << ") Initiated." << endl;
   
	if (number <= 1)
		retVal = 1; 
	else
		retVal = number * factorial(number - 1);
	
   cout<<"Call to factorial(" << number << "). Returning " << retVal << endl;
   return retVal;
}

Output for factorial(3) = 6:

Call to factorial(3) Initiated.
Call to factorial(2) Initiated.
Call to factorial(1) Initiated.
Call to factorial(1). Returning 1
Call to factorial(2). Returning 2
Call to factorial(3). Returning 6

That shows the parameter, and the value returned (which I assume is the 'local variable')

This makes sense, but when i try to build i get the errors:
expected `;' before "number" on line 10
and expected `;' before numeric constant on line 8. but you cant do that. ????

There's probably a typo somewhere. You can try posting your code and someone could probably find it. The code I posted is fine.

This article has been dead for over six months. Start a new discussion instead.