Palindrome is a number or a string, which is same as its reverse. It will be same when read from right to left and left to right.

We Use the following three methods

  1. Using predefined methods like strrev()
  2. Comparing string from start to end
  3. Palindrome in number

Method 1: Using predefined methods like strrev()

Logic:

In this method, we reverse the string, and compare the reversed string with original string.

Algorithm:

  1. Input the string
  2. Use strrev() to reverse the string
  3. Next, we compare both the strings using strcmp
  4. Based on the results, we output the result

 

Code:

#include<iostream.h>
#include<conio.h>
#include <string.h> 
void main()
{
	clrscr();
	char str1[30], str2[30] ;
	cout<<"Enter a string : \n";
	cin>>str1
	strcpy(str2,str1);     //copying str1 in str 2
	strrev(str2);         //reversing string 2 
	if( strcmp(str1, str2) == 0 ) //compare the original and reversed string
		cout<<"\n The string is a palindrome.\n";
	else
		cout<<"\n The string is not a palindrome.\n";
	getch();
}

Output:

Enter a string:

Hello

The string is not a palindrome.

Method 2: Comparing string from start to end

Logic:

In this method, we compare the string from start to end, character by character.

Algorithm:

  1. Input the string
  2. Define i such that i=length of string -1
  3. Now, run a for loop, where the pointer j has starting index and i has ending index
  4. We then compare string[i] and string[j] characters, until i=j.
  5. We change the flag, if character is different
  6. In the end, we check the value of flag with predefined value, and accordingly output the result

Code:

#include <iostream>
#include<string>
using namespace std;
int main()
{	
	string str;
	cout<<"Enter a string: ";
	getline(cin,str);
	int len=str.length();
	int i=len-1;
	int flag=0;
	for (int j = 0; i<j; j++,i--)
	{
		if (str[i] != str[j])
		{
			flag=1;
			cout<<"\n Entered string is not a Palindrome.\n";
			break;
		}
	}
	if (flag==0)
		cout<<"\n Entered string is a Palindrome.\n";
	return 0;
}

Output:

Enter a string: AABBBBAA

Entered string is a Palindrome.

 Method-3 Palindrome with number

This method is already given in one of the examples previously.

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019