Create a C++ program that functions as a palindrome detector using stacks. Progr
ID: 663725 • Letter: C
Question
Create a C++ program that functions as a palindrome detector using stacks.
Program Input: A string of characters and/or numbers, such as “dad,” “sheep,” or “1B34CX149” (Do not worry about or include spaces).
Program Output: The program just simply must state if the string given to the program by the user is a palindrome or not.
An example of how the interface for the user could look in the command prompt:
Please enter a string: kayak
Your string is a palindrome!
or
Please enter a string: jaguar
Your string is not a palindrome!
How to do it:
1. Take the string given to the program by the user and push the string character by character onto the stack. Make sure you save the string given to the program by the user for later use.
2. Once the entire string has been pushed onto the stack, pop the string off the stack character by character, and append each character that gets popped off the stack into a new string.
3. Once the stack is empty, compare the original string given to the program by the user to the new string that has been created by popping the characters off the stack. If the strings are equal, the string is a palindrome
4. The program does not have to worry about upper/lower case palindrome detection (For example: In “Racecar,” since the first ‘r’ is uppercase and the second ‘r’ isn’t, your program doesn’t have to detect it as a palindrome, but it should detect “racecar.”).
Explanation / Answer
A palindrome is a word, character, phrase or a number that contains same letters if read from forward or back.
A C++ program that functions as a palindrome detector using stacks
#include<iostream.h> // header files
#include<conio.h>
void main()
{
clrscr(); // Clear screen
int i,j,len,flag=1; // len tends to length of the character
char a[20]; // a is an array that contains a character of length 20
cout<<"Enter a string:"; //This statement will print " Enter a string"
cin>>a; // the string will be stored in array "a"
for(len=0;a[len]!='';++len); // this is for loop for initializing the value of len to 0 and then will increment its values
for(i=0,j=len-1;i<len/2;++i,--j) // this for loop will repeatedly run and will invert the string
{
if(a[j]!=a[i]) // if jth value of array a is not equal to ith value of array a then
flag=0; //flag=0
}
if(flag==1) // if flag is 1
cout<<" The string is Palindrome"; // then print string is palindrome
else
cout<<" The string is not Palindrome"; // else print it isn't a palindrome
getch();
}