Data Structures and Algorithms Discussion Board
September 10, 2010, 02:42:42 PM *
Welcome, Guest. Please login or register.
Login with username, password and session length
News: Looking for a reliable webhosting provider? Read HostGator review to find 7 arguments in support of HostGator.
 
   Home   Help Search Login Register  
Pages: [1]
  Print  
Author Topic: 2nd problem {URGENT}  (Read 2026 times)
chichi
Newbie
*

Rating: 0
Offline Offline

Posts: 7


« on: April 06, 2009, 01:33:34 PM »

I have to use while loop to redo the compute n! (known as a factorial).
result = n * (n-1) * (n-2) * … * 2
I have to use reference to pass the result to main function for display.
   Hint: use the example below and use following as function prototype
   void factorial(int n, int& result);

Example:
#include <iostream>
using namespace std;
// Compute n! (known as a factorial)
int factorial( int n )
{
int result = 1;
for( int i = n; i > 1; i-- ) // n * (n-1) * (n-2) * … * 2
{
result *= i;
}
return result;
}
int main()
{
int k;
cout<<"Please enter an integer number"<<endl;
cin>>k;
cout<<"The result of "<<k<<"! is "<<factorial(k)<<endl;
return 0;
}
« Last Edit: April 07, 2009, 08:32:24 AM by chichi » Logged
Denis
Newbie
*

Rating: 0
Offline Offline

Posts: 21


« Reply #1 on: April 11, 2009, 10:45:22 AM »

Please, put you code into a code block (# button) next time. Below you can see the solution:

Code:
#include <iostream>
using namespace std;

// Compute n! (known as a factorial)
void factorial(int n, int& result)
{
result = 1;
for( int i = n; i > 1; i-- ) // n * (n-1) * (n-2) * … * 2
{
result *= i;
}
}
int main()
{
int k, fact;
cout<<"Please enter an integer number"<<endl;
cin>>k;
// calculate factorial
factorial(k, fact);
cout<<"The result of "<<k<<"! is "<<fact<<endl;
return 0;
}

1) Factorial function changes, threating result as a local variable, but not declaring it.
2) No need to return the result.
3) main changes. Now we declare fact variable and pass it to factorial function.
 
The trick is when using a reference, local function variable (result) and calling function (main) variable (fact) are sharing the same memory! That's why when writing to the result variable, the fact variable automatically gets the same value.
Logged
Pages: [1]
  Print  
 
Jump to: