Home > Backend Development > C++ > body text

C program to check if a given string is a palindrome?

PHPz
Release: 2023-08-27 14:13:11
forward
814 people have browsed it

C program to check if a given string is a palindrome?

A palindrome is a sequence of words, numbers, phrases, or other characters that is read the same from front to back as it is from back to front. Words like madam or racecar, or numbers like 10801 are palindromes.

For a given string, if the string obtained after reversing the string is the same as the original string, then we can say that the string is a palindrome. This means that to check if a string is a palindrome, we need to find out whether the first and last elements, the second and penultimate elements, and so on are equal.

Input - naman

Output - The string is a palindrome

Input - tutorials point

Output - String is not a palindrome

In C program check if a given string is a palindrome. The input string is copied into a new string, then we compare the first and last letters of the string, the second and penultimate letters, and so on until the end of the string. If the two letters have the same sequence of characters, i.e. they are identical, then the string is a palindrome, otherwise it is not.

Example

#include <iostream>
#include<string.h>
using namespace std; {
   int main(){
      char string1[]={"naman"};
      int i, length;
      int flag = 0;
      length = strlen(string1);
      for(i=0;i < length ;i++){
         if(string1[i] != string1[length-i-1]) {
            flag = 1;
            break;
         }
      }
      if (flag==1){
         printf(" string is not a palindrome");
      } else {
         printf(" string is a palindrome");
      }
      return 0;
   }
}
Copy after login

Output

string is a palindrome
Copy after login

Note - This program is case sensitive.

The above is the detailed content of C program to check if a given string is a palindrome?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template