### Problem with a loop

I am working on project Euler problem #4 which states:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.

Find the largest palindrome made from the product of two 3-digit numbers.

The problem in my program is it only goes through the for loop only one time. I do not understand why its doing it though. Any help is appreciated.

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849`` ``````#include using namespace std; int reverse(int num); int main() { int num; int j; j = 100; int pdn, fi, fj, revNum; fi = 0; fj = 0; pdn = 0; for (int i = 100;i < 999; i++) { int tempj = j; while(j < 999) { num = i * j; revNum = reverse(num); if (num == revNum) { pdn = num; cout << pdn << " pdn" << endl; fi = i; cout << fi << " fi" << endl; fj = j; cout << fj << " fj" << endl; } j++; } j = tempj; j++; } cout << fi << "*" << fj << "=" << pdn << endl; return 0; } int reverse(int num)//ne555 c++ { int result = 0; //`stack' flip while(num){ //num.is_empty() result *= 10; result += num%10; //result.push( num.back() ); num /= 10; //num.pop() } return result; }``````
Last edited on
It actually will go through the for-loop 99 times.
But only on the first pass will the inner `while` loop be executed.

That's because j is initialised to 1 at line 9. Within the loop it is incremented at line 23 until the while loop condition is false.

On the next iteration of the `for` loop, j is already greater than 100, so the `while` loop does not execute.
Last edited on
variable length arrays are not part of the C++ standard.
 ``123456`` `````` int i = numD; int t[i]; int mul = 10; while(i > 0) { t[i]=temp%10; //out of bounds ``````

 ``1234567891011`` ``````int reverse(int num){ int result = 0; //`stack' flip while(num){ //num.is_empty() result *= 10; result += num%10; //result.push( num.back() ); num /= 10; //num.pop() } return result; }``````
Last edited on
Chervil
Thanks That was the problem all along. Works perfect after it.

@ne555
I know my code is really messy I am going to clean it up now.
Also I love your Reverse function! you just did what I was doing in 11 lines of code! Also what did you mean by out of bounds?
Thanks for the help both of you!

Seems like something is still wrong. Because my code found 924 * 962 = 888888 as the largest palindrome number but thats not the right answer -.-
Any suggestions ?
The codes doing what its supposed to be
Last edited on
If you say `T array[N]; //N is a constant ` you've got an array with `N' elements.
You can use an index from 0 to N-1.
However in your code you were trying to access `array[N]`, that's outside the valid range (out-of-bounds)
Topic archived. No new replies allowed.