I have a function below and it is a recursive since it calls itself at the end, but how to I change it non-recursive?
int ACR(int q, int*a, int n, int i){
if(i>=n){
return 0;
}
else{
if(a[i] == q){
return 1;
}
else{
return ACR(q,a,n,i+1);
}
}
}
You can use a loop instead
Each call to the iterative version of
ACRtested whether a single element of the arrayamatched the value ofq. If we reached the end of the array without a match, we returned 0. Its easy to translate this into a loop.Note that
imay no longer be required as an argument if you always want to search the full array (i.e. start at index 0).