I need to sum the members of my progression using recursion. Here's the function which gives my progression and how to count a sum in recursion way?

#include <iostream>

using namespace std;

void progressionRec(int a1, int d, int n) {
    if(n <= 1){
        cout << a1 << " ";
    } else {
        int next = a1 + d;
        progressionRec(next, d, n - 1);
        cout << a1 << " ";
    }
}
int main()
{
    progressionRec(2,3,15);
    return 0;
}

3 Answers

1
C_Raj On Best Solutions

You can sum the members of your progression this way

#include <iostream>

int progressionSum(int a, int d, int n) {
    if (n > 0) {
        return a + progressionSum(a + d, d, n - 1);
    }
    return 0;
}

int main()
{
    std::cout << "Sum: " << progressionSum(2, 3, 15) << std::endl;
    return 0;
}
0
Ayxan On

You may use a functor to store the progress count. Here's an example implementation:

#include <iostream>

using namespace std;

class progressionRec
{
public:
  void operator()(int a1, int d, int n) {
    ++count;
    if(n <= 1){
      cout << a1 << " ";
    } else {
      int next = a1 + d;
      operator()(next, d, n - 1);
      cout << a1 << " ";
    }
  }


  size_t getCount() const
  {
    return count;
  }

private:
  std::size_t count = 0;
};

int main()
{

    auto func = progressionRec();
    func(2,3,15);
    std::cout << "\nCount:" << func.getCount() << std::endl;
    return 0;
}

Output:

44 41 38 35 32 29 26 23 20 17 14 11 8 5 2
Count:15
0
Aleksey On

You need to change returning type of function to int and return sum on each return:return a1 + progressionRec(next, d, n - 1);