Skip to content

Instantly share code, notes, and snippets.

@cristiancrazy
Created May 2, 2024 14:07
Show Gist options
  • Save cristiancrazy/2c7dd7e4c9661e7dac1a92a6cc818e4a to your computer and use it in GitHub Desktop.
Save cristiancrazy/2c7dd7e4c9661e7dac1a92a6cc818e4a to your computer and use it in GitHub Desktop.
/*
Recursive function to:
- Search elements on arrays
- Count elements on arrays
*/
// Find the needle on the a;
// n = the last element index on array
// equals to arraysize-1
int getElement(int a[], int needle, int n){
if(n == 0){
if(needle == a[pos]) return n;
else return -1;
}
if (needle == a[n]){
return n;
}
return getElement(a, needle, n-1);
}
// Find occurrences of the needle on the a;
// n = the last element index on array
// equals to arraysize-1
int countElements(int a[], int needle, int n){
if (n == 0){
return 0;
}
if(a[n] == needle){
return 1+countElements(a, needle, n-1);
}
return countElements(a, needle, n-1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment