I found few posts regarding this problem using C. Most of the elements in my code work on their own but the iteration at the beginning is causing problems for some reason. First, I'm getting an "exited with non-zero status" error message. When I run the program with a smaller range for a and b, I don't get that message. I'm guessing there's a problem with the rev_array and for_array variables I created. I'm sure I'm doing something really dumb right here so I apologize in advance for that.
But when I use a smaller range for a and b (like 10 to 25), the program is still showing that all two-digit numbers (even 11, 22, 33, 44) are not the same forward and backward. I used printf to check for this.
I made a similar program that used fixed values for a and b instead of iterating over a range of values and it worked fine. But I couldn't figure out why this one isn't working.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int max;
int a;
int b;
int prod;
int m = 0;
int rev_array[10000];
int for_array[10000];
int c;
int d;
int same = 0;
int main(void)
{
// iterate over all 3 digit numbers in lines 19-21
for(a = 10; a <= 25; a++)
{
for(b = 10; b <= 25; b++)
{
max = 0;
prod = a * b;
/* thanks to Zach Scrivena for the following formula converting an integer to an array of integers posted on stackoverflow on February 5, 2009 under the subject "convert an integer number into an array"
*/
int n = prod;
while(n != 0)
{
rev_array[m] = n % 10;
n /= 10;
m++;
}
/* thanks to Jordan Lewis for the following int length formula posted to stackoverflow on June 18, 2010 in response to "Finding the length of an integer in C"
*/
int length = floor(log10(abs(prod))) + 1;
// create the forward array of the ints in prod
for(c = length - 1, d = 0; c >= 0; c--, d++)
{
for_array[d] = rev_array[c];
}
// compare the forward and reverse arrays to see if they match exactly
for(int e = 0; e < length; e++)
{
if(for_array[e] != rev_array[e])
{
// if they don't match then set same equal to 1 for following step
same = 1;
}
}
/* if prod is greater than max and the forward and reverse arrays are identical, then replace max with prod
*/
if(prod > max && same == 0)
{
max = prod;
}
// reset same and repeat the process
same = 0;
}
}
// print the final, greatest number that fits the preceding criteria
printf("new max: %i \n", max);
return 0;
}