Question & Answer: Please help with writing the following code. I'm using C++ and vim. Include plenty of comments. Thanks!…..

Please help with writing the following code. I’m using C++ and vim. Include plenty of comments. Thanks!

Dont use any loops when writing your recursive functions. If you do, theres a very good chance your function wont be truly recursive. Also dont use any static variables. You are free to use helper methods on either of the projects

Don’t use any loops when writing your recursive functions. If you do, there’s a very good chance your function won’t be truly recursive. Also don’t use any static variables. You are free to use helper methods on either of the projects

Expert Answer

 

#include <iostream>

#include <string>

using namespace std;

bool isPalindrome(string str) {

int length = str.length(); //this code will find the length of a string

if (length <= 1) { //Since a 1 or 0 length string is always a palindrome

return true; //Hence return true

}

//below condition will executed when string length is less then one

else if (str.at(0) == str.at(length – 1)) { //this line will check whether the first and last char are same or not (if same then only if body will execute)

//below line of code execute only when above condition of if statement is true i.e char at first position is equal to char at last position

//since first and last char are same

//so let focus on 2nd and 2nd last char

//.

//.

//since we have to focus on 2nd and 2nd last char so discard the first and last char now our new string should consist of all character except first and last char

//below code do the above task

//i.e you can assume that from original string first and last char are being removed

str = str.substr(1, (length – 2));

//now perform the same above task for new string i.e

//whether first and last char of new substring is same or not

isPalindrome(str); //and so on .. till our string length become one or 0

}

else { //this part of code will execute only when above else if condition fail so in this case our string is not a palindrom

return false; //hence return false

}

}

//below main will test the correctness of our program

int main() {

string str;

cout << “Please enter the string: “;

cin >> str;

if (isPalindrome(str)) {

cout << “Given string is Palindrome n”;

}

else {

cout << “Given string is not a Palindrome n”;

}

return 0;

}

//Sample output

Still stressed from student homework?
Get quality assistance from academic writers!