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;
              return F(n-1) + (2 * n);


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

9 Years
Discussion Span
Last Post by vmanes

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.