Users Online

· Guests Online: 44

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C++ Program to Check if a String is Palindrome

C++ Program to Check if a String is Palindrome

 

This is a C++ Program to Find if a String is Palindrome.

Problem Description

The program checks if a string is a palindrome or not. A palindrome is a word or a string that reads the same backward and forward.

Problem Solution

1. The program takes a string and stores it.
2. The string is copied into another string from backwards.
3. If both the strings are equal, then the entered string is a palindrome.
4. Else it is not.
5. The result is printed.
6. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Find if a String is Palindrome. The program output is shown below.

  1. #include <iostream>
  2. #include <string.h>
  3. using namespace std;
  4. int main()
  5. {
  6.     char str1[20], str2[20];
  7.     int i, j, len = 0, flag = 0;
  8.     cout << "Enter the string : ";
  9.     gets(str1);
  10.     len = strlen(str1) - 1;
  11.     for (i = len, j = 0; i >= 0 ; i--, j++)
  12.         str2[j] = str1[i];
  13.     if (strcmp(str1, str2))
  14.         flag = 1;
  15.     if (flag == 1)
  16.         cout << str1 << " is not a palindrome";
  17.     else
  18.         cout << str1 << " is a palindrome";
  19.     return 0;
  20. }
Program Explanation

1. The user is asked to enter a string and it is stored in the character variable ‘str1’.
2. The length of str1 is stored in ‘len’ using the string function strlen().
3. Using a for loop, str1 is copied into another variable ‘str2’ from backwards.
4. Both the strings str1 and str2 are compared using string function strcmp().
5. A temporary variable flag is used.
6. If str1 is equal to str2, then the entered string is a palindrome, else not.
7. The result is then printed.

 
Runtime Test Cases
Case 1 :
Enter the string : nun
nun is a palindrome
 
Case 2 :
Enter the string : fast                                                                                                        
fast is not a palindrome
 
Case 3 :
Enter the string : 121                                                                                                         
121 is a palindrome

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.83 seconds
10,819,935 unique visits