Why is it that the cout statement in the recursive function is printing 15, though the one right outside the recursive function (in main) is printing 0. I set num = recursive_function().
Update: I was a noob and returned 0 in the said function. The issue is resolved. Thank you.
#include <iostream>
#include <string>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int sumNumbers(int sum, vector<int> numbers, int count)
{
if ( count == numbers.size() ) {
cout << "The sum of the numbers in the file is: " << sum << endl; - 1st cout statement
return sum;
}
return sumNumbers(sum + numbers[count], numbers, count + 1);
}
int main(int argc, char* argv[])
{
vector<int> numbers;
int numElements = 0;;
int sum;
string fileName = argv[2];
ifstream ifile(fileName);
if( ifile.fail() ) {
cout << "The file could not be opened. The program is terminated." << endl;
return 0;
}
int new_number;
while (ifile >> new_number) numbers.push_back(new_number);
sum = sumNumbers(sum, numbers, 0);
cout << "The sum of the numbers in the file is: " << sum << endl; - 2nd cout statement
return 0;
}
output:
The sum of the numbers in the file is: 15
The sum of the numbers in the file is: 0