0

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);
}
kaylum
  • 13,833
  • 2
  • 22
  • 31
  • Did the answers solve your problem? If the reply is helpful, you could click '✔' to mark it as the accepted answer. It will also help others to solve the similar issue. – Minxin Yu - MSFT May 16 '22 at 06:00

2 Answers2

0

i think you mean

 return lastIndex(arr, size, num);

your code

 return(arr, size, num);

is equivalent to

 return num;
pm100
  • 48,078
  • 23
  • 82
  • 145
  • By any chance, did you try using your debugger to run your program, one line at a time, and see what it does? This is what a debugger is for. If you did, then when your debugger showed that execution reached that line, the very next thing that the debugger will show you next is that the function returns instead of making another recursive call. The problem with then becomes very obvious. Knowing how to effectively use a debugger is a required skill for every C++ developer. Now that you know what the problem is, you should try to use your debugger, and see how obvious this is, in a debugger. – Sam Varshavchik May 14 '22 at 23:30
  • @SamVarshavchik - OP "we havent covered debugging yet", or "my debugger didnt show any errors" – pm100 May 14 '22 at 23:43
0

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);
}
Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42