Code explanation

Can someone explain what does this code do and what it will print out on a console?

#include <iostream>
using namespace std;

void rLS (int a[], int k, int s){
if (s<0)
cout<<"nothing\t";
else if(a[s]==k)
cout<<"yes, a["<< s<<"]\t";

else
return rLS(a,k,s-1);
}
int main()
{
int s=7;
int a[7]={1,3,5,7,9,11,13};
int k=5;
rLS(a,k,s);
rLS(a,9,s);
rLS(a,10,s);
return 0;
}
rLS() is recursive, which means it calls itself.

rLS finds the first matching occurrence of k in array a starting at position s moving backwards through array a (by subtracting 1 on the recursive call)
Last edited on
Use "code tags" when posting code:

[code]
code goes between code tags
[/code]


The first array access is out-of-bounds.
And it's odd to put 'return' in front of a void function call (although g++ and clang++ don't complain).

Maybe it should be more like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

void rLS (int* a, int k, int s)
{
    if (s <= 0)
        cout << k << " not found\n";
    else if (a[--s] == k)
        cout << k << " found at offset " << s << "\n";
    else
        rLS(a, k, s);
}

int main()
{
    int a[] { 1, 3, 5, 7, 9, 11, 13 };
    int s = sizeof a / sizeof *a;
    rLS(a,  5, s);
    rLS(a,  9, s);
    rLS(a, 10, s);
}

Topic archived. No new replies allowed.