Home > front end >  There seems to be a problem with input of only 2 with a size of 6. Everything else seems to work exa
There seems to be a problem with input of only 2 with a size of 6. Everything else seems to work exa

Time:05-15

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:

  1. using namespace std; is bad
  2. int is too small for indexes into arrays, use size_t
  3. passing arrays as pointer size is bad, use std::span
  4. the recursion has to call the function by name
  5. 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);
}
  • Related