Recursion Function with an Array - Help

Hi

The first time the function recurses it changes the searchValue to 1 instead of 5, I really need help with this.

thank you,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

int sortedArray[10] = {0,1,2,3,4,5,6,7,8,9};

void findIndex(int array[], int searchValue, int index);

void findIndex(int array[], int searchValue, int index){
  if(searchValue = array[index]){
    cout << "The index of the value is: " << index << endl;
  }else
    findIndex(array, searchValue, index+1);
}


int main(){

  findIndex(sortedArray, 5, 0);


  system("pause");
}
Hi @venros,

Check this again
line:10 if(searchValue = array[index]) //assignation
is not equal to
if(searchValue == array[index]) //comparing
omg i do this = and == way too much >.>

ty for the fast response.

It works now:

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

using namespace std;

int sortedArray[10] = {0,1,2,3,4,5,6,7,8,9};

void findIndex(int array[], int searchValue, int index);

void findIndex(int array[], int searchValue, int index){
  if(searchValue == array[index]){
    cout << "The index of the value is: " << index << endl;
  }else if(index = 9){
    cout << "The number was not found" << endl;
  }else
    findIndex(array, searchValue, index+1);
}


int main(){

  findIndex(sortedArray, 10, 0);


  system("pause");
}
Last edited on
That's good!
you are welcome!
Topic archived. No new replies allowed.