Search code examples
c++functionbooleanpalindrome

C++ Palindrome Bool Function (Using Pointer)


How to create a Palindrome function in C++? I'm using 2 functions types(bool and void). Here is my code so far (I would really appreciate any help with this, and why my code is not working?) Thank you!

#include <iostream>
#include <cctype>
#include <cstdlib>
#include <string>
using namespace std;


void reverse(char *);  
bool isPalindrome(char *);  

int main()  
{  
    char a[10];  
    cout << "string ";  
    cin.getline(a, 10);  
    if (palindrome(a))  
        cout << "true";   
    else  
        cout << "false";  
    return 0;  
}  
void reverse(char *s)  
{  
    char *point = s;  
    int i, min;  
    for (i = 0; *point != '\0'; i++)  
        point++;  
        min = i;  
        point--;  
    for (i = min; i > 0; i--)  
   {  
        cout << *point--;  
   }  
}  
bool ispalindrome(char *s)  
{  
    bool status;  
    char *original = s;  
    char *point = s;  
    reverse(point);        
    for (int i = 0; point != '\0'; i++)  
    {  
        if (point[i] == original[i])  
        status = true;  
        else  
        status = false;  
    }  
    return status;  
}

Solution

  • you dont need to reverse the string to check if its palindrome.

    the algorithm works like:

    get the length of the string;
    loop from zero to length of string by 2;
    compare the characters on position loop count with lenght minus loop count minus 1;
    if the are not equal its not a palindrom;
    its a palindrome if the loop finished;

    for example: "test":
    first step: compare 't' with 't'
    second step: compare 'e' with 's' --> not a palindrom

    for example "palap":
    first step: compare 'p' with 'p'
    second step: compare 'a' with 'a'
    third step: compare 'l' with 'l'
    now we know that it is a palindrom.

    try thisone:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int palindrom(char * s){
      int i;
      int l = strlen(s);
      for(i=0;i<=l/2;i++)
        if(s[i]!=s[l-i-1]) return 0;
      return 1;
    }
    
    int main(void) {
      char * test = "test";
      char * pal = "palap";
      printf("%s %d", test, palindrom(test));
      printf("%s %d", pal, palindrom(pal));
      return 0; 
    }