Recursion problem

Hello Kamikaze24,

I tried to run your program, but it did not compile.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
//#include <fstream>    // <--- Not used at this time. Did you have a future use for it?
//#include <cstring>  // <--- The program uses nothing from this header file. Is there a reason for it?
#include <cassert>
#include <string>

using namespace std;

bool match(string chars, int i, string source, int j)
{
    // pre-condition: assert (i <= chars.length()-1 && j <= source.length()-1);

    if (i < chars.length() - 1 && j == source.length() - 1)
        return false;

    else if (i == chars.length() - 1 && j == source.length() - 1)
        return chars[i] == source[j];

    else
    {
        if (chars[i] != source[j])
            match(chars, i, source, j + 1);
        else
            return match(chars, i + 1, source, j);
    }
}

int main()
{
    cout << match_chars("ilj", 0, "I hate peanuts", 0);
}

Blank lines are nice, but you use to many. Double spacing is not necessary.

Watch you indenting. It really helps.

Notice your function definition and function call. These need to match.

I am not great with recursive function, so it will take a little time to see what it is doing.

Lines 14 and 18 produce a warning. Not enough to stop the kprogram from running.

The string functions ".length()" and ".size()" both return a value of "size_t". This is an "unsigned" variable, so when you compare a "signed int" to an "size_t", (unsigned something), there is a type mismatch. There is also a mismatch because "size_t" could be an "int" or a "long". Something to be aware of, but not usually a problem.

Andy
Hello Kamikaze24,

Your second code is no longer a recursive function. I think lines 22 and 24 should start with "return".

This not an exact match to what you are doing, but might help https://beginnersbook.com/2017/08/cpp-recursion/

Andy
OP has now deleted their posts!!!!!!!!


Topic archived. No new replies allowed.