Monday, 9 September 2013

C changing variable inside while loop

C changing variable inside while loop

I'm new to C++, and trying to go through Project Euler. I got all the way
to Problem 4 (impressive I know) and am having trouble with what I think
is the scope of my variables inside a while loop. If you don't know, the
problem asks you to find the highest palindrome product of two three digit
integers. I made a while loop which should test if a product is a
palindrome (which I put into another function - which works fine).
Here's my current code (although it's changed many times - I tried to make
this one the most definite, which is why all the else ifs):
int main()
{
int int1 = 999;
int int2 = 999;
int nProduct = int1 * int2;
int nFinalProduct = 0;
while (int1 >= 100)
{
if (paltest(nProduct) == 1 && nProduct > nFinalProduct && int2 > 100)
{
nFinalProduct = nProduct;
--int2;
}
else if (paltest(nProduct) == 1 && nProduct > nFinalProduct
&& int2 == 100)
{
nFinalProduct = nProduct;
--int1;
}
else if (paltest(nProduct) == 0 && int2 > 100)
{
--int2;
}
else if (paltest(nProduct) == 0 && int2 == 100)
{
--int1;
}
}
cout << nFinalProduct;
}
I'm basically trying to say if the product is a palindrome AND higher than
the previous one, add it to nFinalProduct, and decrement int1 or int2 to
get the next product.
I've tried rewriting main() several times using the same kind of logic,
but each time the output doesn't change from what I initialise
nFinalProduct to (in this case 0). Is it only updating the value inside
the while loop and then resetting it once the loop ends? My solution for
Project Euler's third problem uses the same idea of initialising a
variable, changing it inside a while loop and printing it outside the
loop, which works fine. I can't think of what the problem here is, except
maybe if it's never finding paltest() to be 1, which I've tested heaps and
cant find a problem with.
Any help is appreciated.

No comments:

Post a Comment