Scott Obray
Scott Obray

Reputation: 3

C++ Palindrome Creator Recursion Program

#include <iostream>
using namespace std;


void palindrome(char *s){
    if (s[1] == 0)
    {
        return;
    }
    cout << s[0];
    palindrome(++s);
    cout << s[0];
}


int main(){
    char s[30]="foobar";
    palindrome(s);
    cout << endl;
}

I have to create a recursive function that turns any cstring into a palindrome. This is a homework question and the only code I can modify is inside the palindrome function. This code almost works. The problem is it returns "foobaraboo" and leaves off the last letter. Any tips to point me in the right direction? I've played around with the code for quite a while and can't seem to figure out how to change it so the last character of the palindrome shows up.

Upvotes: 0

Views: 872

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

Here you are

#include <iostream>

void palindrome( const char *s )
{
    if ( s[0] )
    {        
        std::cout << s[0];
        if ( s[1] )
        {            
            palindrome( s + 1 );
            std::cout << s[0];
        }
    }        
}

int main()
{
    const char *s = "foobar";
    palindrome( s );
    std::cout << std::endl;

}    

The program output is

foobaraboof

Upvotes: 0

Sam Varshavchik
Sam Varshavchik

Reputation: 118435

You have two bugs in your logic. The first one:

if (s[1] == 0)
{
    return;
}

This should be:

if (*s == 0)
{
    return;
}

if your entire input is the string "x", your expected result is the palindrom "xx", but this bug will result in an empty string getting printed.

You also have a more fundamental bug:

cout << s[0];
palindrome(++s);
cout << s[0];

Your intent here is to print the current character, recursively print the rest of the palindrome string, and then re-print the same character.

But because of the ++s, you're printing the wrong character, the second time around.

This should be:

cout << s[0];
palindrome(s+1);
cout << s[0];

EDIT: a question has been raised whether you want the last character printed twice. If not, then this should be:

cout << s[0];
if (s[1])
{
    palindrome(s+1);
    cout << s[0];
}

Upvotes: 1

Related Questions