Exactly so, cblack618.
Inside any given function, the following variables exist:
1) Parameters that were pass in to the function.
2) Variables you create within that function
3) Global variables that exist everywhere
4) In a class object, member variables of that class.
In this case, your function is very simple, and the variables that exist are only the parameters passed in;
str,
lower, and
upper. As you surmise, you meant to use
lower and
upper.
With that, your palindrome function is complete and works!
1 2 3 4 5 6 7 8 9 10
|
bool isPalindrome(string str, int lower, int upper)
{
if (lower >= upper)
return true;
if (str[lower] != str[upper])
return false;
return isPalindrome(str, lower + 1, upper - 1);
}
|
Good job!
Note, however, that you've made a similar mistake in your
main function.
These line:
1 2
|
string word;
int stringLength = str.length();
|
(note that you missed the
=
in that second line there!)
In this line, you're trying to use a string named
str to get the length, but your string was actually named
word in the line above. Your logic is correct; you made a silly mistake there.
You're also trying to fetch the length of the string before the user entered it! Again, I can see the logic of what you're trying, the logic is correct, but you got it mixed up.
Here's the final, corrected version;
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
|
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(string str, int lower, int upper)
{
if (lower >= upper)
return true;
if (str[lower] != str[upper])
return false;
return isPalindrome(str, lower + 1, upper - 1);
}
int main()
{
// Get the word from the user...
string word;
cout << "Enter a word to see if its a palindrome" << endl;
getline(cin, word);
// And THEN you can calulate the length of the word!
int stringLength = word.length();
if (isPalindrome(word, 0, stringLength - 1))
cout << word << " : is a palindrome." << endl;
else
cout << word << " : is not a palindrome." << endl;
return 0;
}
|
So well done, you got there, and that's what matters. Hopefully you've actually understood how to think about recursive functions. The basics are simple enough; they either return a value, or call themselves again with different parameters.
A shame the thread is interspersed by today's racist troll, but that's the internet for you, I suppose.