I'm new to C++, and trying to go through [Project Euler][1]. I got all the way to [Problem 4][2] (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.
UPDATE: Ok guys, thanks heaps. I moved the nProduct declaration to inside the while loop, and now it wont end. This is my new code:
int main(){
int int1 = 999;
int int2 = 999;
int nFinalProduct = 0;
while (int1 >= 100){
int nProduct = int1 * int2;
if (paltest(nProduct) == 1 && nProduct > nFinalProduct && int2 > 100){
nFinalProduct = nProduct;
--int2;
}
else if (paltest(nProduct) == 1 && nProduct > nFinalProduct && int2 == 100){
nFinalProduct = nProduct;
int2 = 999;
--int1;
}
else if (paltest(nProduct) == 0 && int2 > 100){
--int2;
}
else if (paltest(nProduct) == 0 && int2 == 100){
int2 = 999;
--int1;
}
}
cout << nFinalProduct;
}
Which now will just run indefinitely. My feeling is that int1 is never being decremented (which would eventually terminate the loop). If it's not being decremented, it means that int2 is never decrementing. Am I on the right track?
[1] https://projecteuler.net [2] https://projecteuler.net/problem=4