Recursion array is it right?

Hi All,

I am doing an excersise with recursion having correct return codes. If it matches or not matches an array element. I have managed to do it using a global variable but it doesn't seem that clean. Or is the right way to do it?

Any help would be greatly appreciated.

Here is the question :

Write a recursive function that takes a sorted array and a target element and finds that element in the array (returning the index, or -1 if the element isn’t in the array). How fast can you make this search? Can you do better than looking having to look at every element?

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
 
#include <iostream>

using namespace std;

int code = -1;

int Num( int arr[], int size, int target)

{
  

    
     if ( size < 4) {
         
         if (target == arr[size]) {
             cout << "*found" << endl;
           //Returns code so doesnt go through entire array
            return code = 2;
         }
      
          Num(arr, size + 1, target);
     }
    
    return code;
}
     
     
int main () {
     
     int x = 0;
     int array [6] = { 1, 2, 3, 4, 5, 0 };

     cout << Num( array, x, 8 ) << endl;;
    
}
Last edited on
It would be nice to have some descriptive symbolic names for your constants. F.e. I don't understand these mystical values on line 14 an 19.

You don't need a global variable to return any value of your function.

But you should take care of the return code of any function returning a value in any cases.
Topic archived. No new replies allowed.