'I want to sum all my vector indexes with a recursive function but starting backwards

I am stuck with this program so far, and I don't know what else to do.

I just need help with the recursive function so I can do the other modes too, which are multiplication and subtraction.

#include "std_lib_facilities.h"
//this contains all the libraries my university offers. 

int sum(vector <int> test, int i){
    if (i < 0){
        return 0;
    }
    else {
        return test[i] + sum(test, i - 1);
    }
}

int main(){
    int n;
    int x;
    int mode;
    int result = 0;
    cout << "give the size of the vector:\n";
    cin >> n;
    while (n < 0){
        cout << "you can't give negative number!give again:\n";
        cin >> n;
    }
    vector <int> myvector;

    for (int i = 0; i <= n-1; i++){
        cout << "give numbers to fill the vector:\n";
        cin >> x;
        myvector.push_back(x);
    }
    cout << "give 1 for sum 2 for multiplication 3 for substraction\n";
    cin >> mode;
    while (mode < 1 && mode > 3){
        cout << "this mode doesn't exist.give again:\n";
        cin >> mode;
    }
    if (mode == 1){
        result = sum(myvector, n);
        cout << "result is:" << result;
    }
}

I want to get all the indexes starting from backwards to sum them all.



Solution 1:[1]

You are accessing outside the bounds of your array.

The simple fix to your issue is to pass n-1 to your sum function.

result=sum(myvector,n - 1);

However, there is no need for you to pass n at all, rather i would suggest you add a function that starts the recursion like this. (this is a rather common pattern for recursion)

int sum(const vector<int>& test, int i);

int sum(const vector<int>& test)
{
    if(test.empty())
    {
        return 0;
    }

    if(test.size() == 1)
    {
        return test[0];
    }

    return sum(test, test.size() - 1);
};

int sum(const vector<int>& test, int i) 
{
    if(i < 0)
    {
        return 0;
    }

    return test[i] + sum(test, i - 1);
};

then call it like sum(myvector);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Taekahn