user81883
user81883

Reputation: 123

Verification for code to check if a number is a palindrome

#include <iostream>
 #include "conio.h"
 #include <math.h>

 using namespace std;

void main()
{
    int n;
    int sum=0;
    int a[16];
    cin>>n;
    int i=0;
    while(n>0)
    {

        a[i]=n%10;
        n=n/10;
        i++;
    }
    for(int j=0;j<=i;j++)
    {
        if(a[j]!=a[i-j])
        {
            sum=1;
        }
    }
    if(sum==1)
        cout<<"not a palindrome";
    else
        cout<<" palindrome";
    _getch();
}

I typed the above code to check whether a number is a palindrome but I keep getting that it's not a palindrome irrespective of the number I enter. Where have I gone wrong ?

Upvotes: 0

Views: 123

Answers (2)

doctorlove
doctorlove

Reputation: 19272

You simply have an off by one error: Change this

if(a[j]!=a[i-j]){

to

if(a[j]!=a[i-j-1]){

For example, conside 11. Then i is 2, so i-j is 2-0 i.e. 2, when j is 0, which means you compare a[0] with a[2], not a[1].

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 71009

After the end of the while cycle i will store the number of elements in a. So in the cycle above you should compare a[0] (the first element) to a[i-1] (the last element). Instead you compare a[0] to a[i] which is not a digit of the number. Think of how you can fix that.

Upvotes: 5

Related Questions