I was solving an example to improve my C++, though I couldn't solve it the way it's meant to be. The problem says:
Write a recursive function that will compute the sum of the first n integers in an array of at least n integers. Hint: begin with nth integer.
here's my solution:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int temp;
int integerSummer(vector<int> new_one, int n)
{
if(n == 0)
return 0;
else
temp = new_one[n];
return temp + integerSummer(new_one, n - 1);
}
int main()
{
vector<int> new_one;
new_one[0] = 11;
new_one[1] = 20;
new_one[2] = 21;
new_one[3] = 17;
new_one[4] = 5;
integerSummer(new_one, 3);
system("pause");
return 0;
}
Program exits immediately after executing it. What's wrong with the code? Any ideas?
Write a recursive function that will compute the sum of the first n integers in an array of at least n integers. Hint: begin with nth integer.
here's my solution:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int temp;
int integerSummer(vector<int> new_one, int n)
{
if(n == 0)
return 0;
else
temp = new_one[n];
return temp + integerSummer(new_one, n - 1);
}
int main()
{
vector<int> new_one;
new_one[0] = 11;
new_one[1] = 20;
new_one[2] = 21;
new_one[3] = 17;
new_one[4] = 5;
integerSummer(new_one, 3);
system("pause");
return 0;
}
Program exits immediately after executing it. What's wrong with the code? Any ideas?