Write a program that reads a word into a C-string (a character array). The program should then determine whether the word would be a palindrome if we remove the first character and add it at the back of the word. Use only C-string functions and C-strings.
so for example
Banana
if we take the B and add it to the back , ananaB it will become a Palindrome.
Can anyone help with this please?
#include <stdio.h>
#include <string.h>
int main(){
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string: ");
scanf("%s", string1);
length = strlen(string1);
for(i=0;i < length ;i++){
if(string1[i] != string1[length-i-1]){
flag = 1;
break;
}
}
if (flag) {
printf("%s is not a palindrome ", string1);
}
else {
printf("%s is a palindrome ", string1);
}
return 0;
}
This is what I got so far, its not entirely correct but atleast it can read if its palindrome or not
Removing the first character in a string and pushing onto the back of the string doesn't automatically transform a non-palindrome into is-a-palindrome.
ananaB is still not a palindrome, a word or phrase that reads the same forwards and backwards.
Copy the first letter in the string and appending it to the end can make the word a palindrome, or it might not.
This is an interesting question. I wrote a code which seems clever to me because it compares the first half of a word with its second part starting at the end. Maybe it is too complicated for a beginner because of the lower case conversion or the "short" boolean at end. However it works fine as expected. I hope it helps you ++
#include <iostream>
#include <algorithm>
#include <string>
bool isPalindrome(std::string word)
{
char letterFromStart; // char starting at the beginning
char letterFromEnd; // char starting from the end of the string
for (int i = 0; i < (word.length() / 2); i++)
{
letterFromStart = word[i];
letterFromEnd = word[(word.length() - 1) - i];
if (letterFromStart != letterFromEnd) returnfalse;
}
returntrue;
}
bool isPalindrome(std::string word);
int main()
{ // some words
std::string words[4] = { "Level", "rAbbit", "raDar", "poTAtoe" };
// convert each word to lower case
for (std::string& s : words)
std::for_each(s.begin(), s.end(), [](char& c) { c = std::tolower(static_cast<unsignedchar>(c)); });
// check all words in our array
for (int i = 0; i < *(&words + 1) - words; i++)
if (isPalindrome(words[i]) ? std::cout << words[i] << " is a palindrome" << std::endl
: std::cout << words[i] << " is NOT a palindrome" << std::endl);
return 0;
}
level is a palindrome
rabbit is NOT a palindrome
radar is a palindrome
potatoe is NOT a palindrome
Adding the first letter to the end means that the first and last letters are always panindromic. So you can instead just check if the word is a palindrome starting with the second letter.