Palindrome

Feb 26, 2017 at 8:04pm
The exercise is:
I need to display all of the numbers that are palindromes and are part of the [a,b] interval; a and b are introduced from the keyboard.
Down below is the code I've written so far,but I don't really know how I should continue..I'm stuck.
I'm a beginner,so please do not use functions or more advanced stuff.Also,please include explanations in the code if possible,so I could understand.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    int a,b,n,copie,invers=0,i,c;
    cout<<"a=";cin>>a;
    cout<<"b=";cin>>b;
    for(i=a;i<=b;i++)
    {
        cout<<"n=";cin>>n;
        copie=n;
        while(n)
        {
            c=n%10;
            invers=invers*10+c;
            n=n/10;
        }
        if(invers==copie)cout<<"The numbers are: "<<copie<<endl;
    }

Feb 26, 2017 at 9:50pm
i is the variable looping from a to b, but you're using n inside the loop. Change line 6 to n=i;

You compute invers to be the reverse digits of n, but you set it to zero outside the loop. So invers will get the right value the first time through, but after that, it will contain incorrect values. Add invers=0; at the beginning of the while loop.
Topic archived. No new replies allowed.