Im trying to Write a Recursive funtion that computes F(n) = 2 + 4 + 6 +...+2n using pass by reference.. here is the code I have

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int F(int &);

int main(){

int n;

         cout <<"Enter n for computing F(n) : ";
         cin >> n;


          cout <<"F(  " << n <<" ) = " << F(n);

return 0;
}

int F(int &){

          if ( n==0)
                return 0;

          if (n==1)
              return 2;
          else
              return F(n-1) + (2 * n);

}

I keep getting an error any help would be greatly appreciated.

Recommended Answers

All 2 Replies

line 22: you have to give the parameter a variable name. int F(int &n)

Why is the argument passed by reference? You are returning the result directly.

Reference parameters in recursive functions are tricky things - every instance of the function may be modifying the same object in memory. And you cannot use the reference parameter in the expression return F( n-1 ).... because the function F() is expecting a variable, not the result of an expression.

Lastly, if you in fact modified the reference parameter, consider what happens to your variable n in main( ). The output statement:

cout <<"F(  " << n <<" ) = " << F(n);

would display the modified value of n in both places. Multiple output statements like that are built up from the right to the left, so the function would execute, modifying n, and that modified n is what would show up in the first display of n as well. Another reason not to use reference parameter in this case.
Val

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.