'There seems to be a problem with input of only 2 with a size of 6. Everything else seems to work exactly as expected. Why is this happening

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);
}


Solution 1:[1]

i think you mean

 return lastIndex(arr, size, num);

your code

 return(arr, size, num);

is equivalent to

 return num;

Solution 2:[2]

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);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pm100
Solution 2 Goswin von Brederlow