My problem here is that I do not get why I cannot get the desired sum of the array's random numbers. Could anyone help me to figure out the error, please?
#include <iostream>
using namespace std;
class Recursion{
int max_size;
double sum;
int index;
double* arr;
public:
Recursion(int);
void fill_array();
void sum_array();
};
Recursion::Recursion(int size){//from main
max_size = size;
sum = 0;
index = 0;
arr = new double[max_size];
}
void Recursion::fill_array(){
if (index == max_size){
cout << "Array is Full." << endl;
//stop array
}
else{
arr[index] = rand() % 10+1;
cout << arr[index] << endl;
index++;
fill_array();
}
}
void Recursion::sum_array(){
if (index == max_size){
cout << "Sum is: "<< sum << "!"<< endl;
}
else{
sum = sum + arr[index];
index++;
sum_array();
}
}
int main(){
Recursion connect(5);
connect.fill_array();
connect.sum_array();
return 0;
}
The output is:
8
10
4
9
1
Array is Full.
Sum is: 0!