How to check in character?

Jan 7, 2019 at 8:02pm
Hi...
This program check numbers that is palindrome or not in reverse order i want to make this program for characters checks palindrome or not like(MOM,MADAM)...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 #include<iostream>
using namespace std;
main()
{
	long int n, num, digit, rev=0;
	cout<<" Enter  a  positive  number:";
	cin>>num;
	n=num;
	do
	{
		digit=num%10;
		rev=(rev*10)+digit;
		num=num/10;
	}
	while(num!=0);
	cout<<" The  reverse  of  the  number  is : "<<rev<<endl;
	if(n==rev)
	cout<<" The  number  is  palindrome";
	else
	cout<<" The  number  is  not  palindrome";
}
Last edited on Jan 7, 2019 at 8:08pm
Jan 7, 2019 at 8:25pm
What's stopping you?
Jan 7, 2019 at 8:55pm
how to make??
Jan 7, 2019 at 9:23pm
just start checking from front and behind till the middle. if any char mismatches then not palindrome. if u reach middle with all char matching then its a palindrome.
Jan 7, 2019 at 9:43pm
how??
Jan 8, 2019 at 2:32am
Do it like you did it with numbers.

First, take a string.
Iterate from its last index to its first index and for every character, append to a new string (just like how you appended to rev using maths but here you do it directly).

Compare both strings. And voila you're done.

Quick mentions:
1) Strings have an operator for +, so you can use += to append to a string.
2) You can use .length() or .size() on a string to get its size.
3) You have to iterate from last index to first index, keep in mind (or you could reserve memory on the second string and use indexes).
4) If you were to use cstrings then do the same but with strlen() instead and you can use strcmp() for comparing (for strings you can just use == operator).
Jan 8, 2019 at 8:30pm
Well @Grime's approach would work but if you want to save the extra space, then you could do:-
1
2
3
4
5
6
7
8
9
10
11
12
13
s = "MADAM"
l = 0
r = len(s) - 1
while(l < r){
 if(s[i] != s[r]){
   print("Not a palindrome");
   break;
}
l++;
r--;
}
if(l >= r)
   print("Palindrome")
Jan 9, 2019 at 10:54am
Thanks Grime and honeybuzz
Topic archived. No new replies allowed.