Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ program A palindrome is a word that reads the same way forward and backward,

ID: 3798918 • Letter: C

Question

C++ program

A palindrome is a word that reads the same way forward and backward, such as "dad" or "deed". You can determine if a word is a palindrome using a stack as follows: 1. Determine the length, n, of the word w. 2. Push the first n/2 characters of w, one at a time, onto a stack s. Each character pushed onto s is removed from w. 3. If n is odd, remove the first character of w. 4. If s is empty, then stop and declare w to be a palindrome. 5. Now, compare the top character in s with the the first letter of what remains in w. If the letters are the same pop the top letter from s, remove the cooresponding letter from w and go back to step 4. If the letters are not the same, then stop and declare w to be a non-palindrome. Write a function called isPalindrome which uses a stack of characters to implement the above algorithm. Note, isPalindrome takes a single string paramenter w and returns true if w is a palindrome and returns false otherwise.

Explanation / Answer

These are the variables and function declarations required :-

void push(char);

char pop();
  
bool isPalindeome();

char stack[100];

int top = -1;

isPalindrome() Function definition:-


    bool isPalindeome()
    {

        char str[100];

        int i, count = 0, len,flag = 0,mid;

   

        printf("Enter string to check it is palindrome or not : ");

        scanf("%s", str);

   
        //Determine the length, n, of the word str
        len = strlen(str);
      
        if(len%2 == 0){
            mid = len/2;
        }else{
            mid = len/2 + 1;
        }
   
        //Push the first n/2 characters of str, one at a time, onto a stack
        for (i = 0; i < mid; i++)
        {

            push(str[i]);

        }
        //If n is odd, remove the first character of stack
        if(len%2 == 1){
            pop();
        }

        //If the letters are the samei pop the top letter from stack
        //If the letters are not the same while popping, then stop and declare str to be a non-palindrome.
        for (i = mid; i < len; i++)

        {
            if (str[i] != pop())
               return false;
        }

      return true;
    }

Push(char) function definition :-

void push(char c)

    {

        stack[++top] = c;

    }


Pop() Function Definition :-

char pop()

    {

        return(stack[top--]);

    }

Output:-

Enter string to check it is palindrome or not :

sumanth
sumanth is not a palindrome string

Enter string to check it is palindrome or not :
adda
adda is a palindrome string

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote