-1

I have written the following code for finding the first palindrome obtained by product of two 3 digit numbers:

#include <stdio.h>

int main()
{
    int pro,d,sum=0,c;
    for (int a=100;a<1000;a++)
    {
        for (int b=a;b<1000;b++)
        {
            pro=a*b;
            d=pro;
            while (d!=0)
            {
                c=d%10;
                sum= sum*10 + c;
                d=d/10;
            }

            if (sum==pro)
            {
                printf("%d is a palindrome \n",sum);
                return 0;
            }
        }
   }
   return 0;
}

But when I run the code it doesn't give me any output. Any helps?

klutt
  • 30,332
  • 17
  • 55
  • 95
  • 2
    You need to reset the sum before reversing the digits – DDMC Sep 23 '18 at 02:13
  • Moving `int sum = 0;` inside of the scope where it is needed will always work (e.g. inside the `for (int b=a;b<1000;b++)` loop) In fact you could move all your variable declarations there since none are used outside that scope. – David C. Rankin Sep 23 '18 at 02:22

1 Answers1

0

You need to reset the sum value after every iteration or inner for loop otherwise it used the previous iteration value in next subsequent iteration.

Code :

#include <stdio.h>

int main()
{
   int pro,d,sum=0,c;
 for (int a=100;a<1000;a++)
{
    for (int b=a;b<1000;b++)
    {
        pro=a*b;
        d=pro;
        while (d!=0)
        {
            c=d%10;
            sum= sum*10 + c;
            d=d/10;
        }
        if (sum==pro)
        {
            printf("%d is a palindrome \n",sum);
            return 0;
        }
        sum=0;
    }
}

    return 0;
}

Output :

10201 is a palindrome
Usman
  • 1,983
  • 15
  • 28