c++ recursion pls help

I need help to write program which checks if number is between [-21,7; 132,234] in string, using recursion. When i run the code I get exit status -1.(sorry for bad English).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    #include <iostream>
    #include <vector>
    using namespace std;
    
    int function(vector <float> vec, int i)
    {
      if (vec[i] > -21,5 && vec[i] < 132,234)
      {
        cout << vec[i];
        return i + function(vec, i + 1);
      }
      
      if (vec[i] < -21,5 && vec[i] > 132,234)
      {
        return i + function(vec, i + 1);
      }
    
      else 
      {
        return 0;
      }
    }
    
    int main() 
    {
      vector <float> vec;
      int n;
      cout << "Enter N: ";
      cin >> n;
    
      for (int i = 0; i < n; i++)
      {
        cout << "Enter vec: ";
        cin >> vec[i];
      }
      
      cout << function(vec, 0);
    
      return 0;
    }
Last edited on
First, change your numeric literals to use a decimal point instead of a comma.
-21,5 becomes -21.5

Second, why does function return an int? What does that integer mean?

Third, a recursion function must have a terminating condition, otherwise it will keep running until you run out of stack space. I suggest you check your i variable against the size of vec. When i becomes too big to be a valid offset into vec, return without doing another recursion.
Topic archived. No new replies allowed.