Iteration to Recursive

hello all,the practice assignment im working on is to have two functions that will search each character of two strings and compare them to each other, if any characters are different the functions will return false. the two functions do the same thing, but they take a different approach. One is iterative (super easy) and one is recursive (super hard). here are my two functions. I Can't figure out why the recursive is returning true when I type word 1: abcd, and word 2: abzd. Any input would be appreciated :)

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
  #include <string>
#include <iostream>
using namespace std;
bool recursive(string, string, int);
bool iterative(string, string);
int main()
{
	string one, two;
	cout << "enter 1\n";
	cin >> one;
	cout << "enter 2\n";
	cin >> two;

	if (recursive(one, two, 0))
	{
		cout << "recursive: true\n";
	}
	else
		cout << "recursive: False\n";
	if (iterative(one, two))
	{
		cout << "iterative true";
	}
	else
		cout << "iterative false";
}

bool recursive(string one, string two, int i)
{

	if (one.size() != two.size())
	{
		return false;
	}
	if (i = one.size())
	{
		return true;
	}
	if (one[i] != two[i])
	{
		return false;
	}
	if (one[i] == two[i])
	{
		if (recursive(one, two, i++))
		{
			return true;
		}
		 return false;
	}
}

bool iterative(string one, string two)
{
	if (one.size() != two.size())
	{
		return false;
	}
	for (int i = 0; i<one.size(); i++)
	{
		if (one[i] != two[i])
		{
			return false;
		}
	}
	return true;

}
Line 35 is a problem.

EDIT - you also might want to wrap the recursive call in a loop so you can call it until you base case

if (i == one.size() || i == two.size())

checks out. Then you can return true or false.
Last edited on
Topic archived. No new replies allowed.