I am starting to learn c . So I want to try this using only recursion.Thank You for your help.
#include <iostream>
using namespace std;
int lastIndex(int arr[], int size, int num){
size--;
if(size < 0)return -1;
if(arr[size] == num)return size;
return(arr, size, num);
}
int main(){
int arr[11] = {1, 2, 2, 4, 2, 8};
cout << "Last Index = " << lastIndex(arr, 6, 2);
}
CodePudding user response:
i think you mean
return lastIndex(arr, size, num);
your code
return(arr, size, num);
is equivalent to
return num;
CodePudding user response:
Things I fixed for your code:
- using namespace std; is bad
- int is too small for indexes into arrays, use size_t
- passing arrays as pointer size is bad, use std::span
- the recursion has to call the function by name
- C arrays are bad, use std::vector or std::array
#include <iostream>
#include <array>
#include <span>
size_t lastIndex(std::span<int> span, int num) {
if (span.empty()) return -1;
if (span.back() == num) return span.size();
return lastIndex(span.first(span.size() - 1), num);
}
int main(){
std::array<int, 6> arr = {1, 2, 2, 4, 2, 8};
std::cout << "Last Index = " << lastIndex(arr, 2);
}