Search code examples
c++recursiontail-recursion

Recursion function to calculate the sum of squares in a sequence (and output the process)


int SeriesToOne(int n) {
   if (n == 1) {
       cout << "(" << 1 << "*" << 1 << ") = ";
       return 1;
   }
   cout << "(" << n << "*" << n << ") + ";
return (n * n) + SeriesToOne(n - 1); }

Hey so I'm writing a program thats supposed to calculate the sum of squares in a sequence using recursion.

I'm writing two functions, one that calculates it going from 1 to N and one that calculates it going from N to 1, and outputting the process. The above code is the function that I wrote for N to 1, but I'm having a lot of trouble with going from 1 to N.

I don't know how to properly write out the base case and get to that base case without adding a second argument to the function (the assignment specifies one argument).

If anyone could help me out, that'd be awesome! And sorry if I didn't format this post or put it in the wrong section, first time poster.


Solution

  • Ok, so as you need to know the value of n inside the recursion function because of the base condition, you can either declare variable as global or you can pass it to function in every call like below:

    int SeriesToN(int n, int N) {
        if (n == N) {
            cout << "(" << n << "*" << n << ") = ";
            return n * n;
        }
        cout << "(" << n << "*" << n << ") + ";
        return (n * n) + SeriesToN(n + 1, N); 
    }
    

    Then call the function like follow if n = 4:

    SeriesToN(1, 4);
    

    This should solve you problem. Happy coding!