solution for q4.cpp

This program has to ask the user for a word “string” and print out “true” in case, the word can be spelled backwards just as it would be spelled normaly (palindromes). If the inverse is different to the actual word, then the program needs to print out “false”.

here are some examples of palindromes:

ana
lol
sos
bob
mom
dad

In order to do this, we will ask the user for a string and use a function to reverse it (change the position of every letter) and compare it to the original word. For this to work, we have to make sure to include the correct libraries:

After having these libraries, we need to create 2 variables (strings) in order to receive the word, (two times in this case) and store its original value in the second string. After doing this, we will invert the word and compare it two the second variable (the original word is stored here) and check if it is indeed a palindrome or not. In order to do this, we will be using a function called reverse:

word= string(word.rbegin(), word.rend()); //where “word” is our variable to be inverted//

So the program should ask the user for a word, store it and then ask for it again (in order to keep the original value in a different variable). After doing this, it should use the function for reverse shown above and invert the initial variable. Using a “if, else” conditional, we can print out “true” or “false” depending if the conditional was proven:

if (word == newword){

cout<<” true “;

}else {

cout<<” false “;

}

//where word is the first variable and newword is the second one//

here is a picture of how the could should look and how it should run:

 

CC BY 4.0 solution for q4.cpp by carlos green is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.