1. ## nested for loop

Good evening,

I'm glad to be a new member for this board.

For an exercise, I must find all integer solutions to the equation x^2 + y ^2 = 1600, where x >= 0 and y >= 0 and I can't have reversed numbers, for instance, x = 0 and y = 40 or x = 40 and y = 0.

I was thinking of starting x = 0 and incrementing it and having y = 40 decrementing that. With that initial though, I was created this skeleton.

main()
{
int x, y;

for (x = 0; x <= 40; x++)
{

}

for (y = 40; y >= 0; y--)
{

}
}

I was wondering if this would hold as a possibility for this program and if anyone can help me set me mind to test numbers. This is my first time using a nested loop of any sort and the logic confuses me. Any help would be great. I don't need any coding, just some direction.

Thank you

2. Just for future reference, it would be a good idea to use code tags around your code.

Anyway, as for nested loops, if you did something like this:
Code:
```for(x=0; x <= 40; x++)
{
for(y=0; y <= 40; y++)
{
if( ( (x*x) + (y*y) == 1600)&&(x < y) )
{
/* Do some stuff here */
}
}
}```
This works by setting x = 0, y = 0 and then slowly incrementing them one by one. In other words, the inner loop will get executed 40 times for each time the outer loop is executed once.
I.e. Iteration 1 - x = 0; y = 0
Iteration 2 - x = 0; y = 1
etc
Iteration 41 - x = 0; y = 40
Iteration 42 - x = 1; y = 0
etc
Iteration 81 - x = 1; y = 40
Iteration 82 - x = 2; y = 0
And so on, so forth.

I included the x < y statement in the if statement so that you don't get opposite repeats (e.g. x = 0, y = 40 and x = 40 and y = 0 will come out once as a solution). There are alternative methods of limiting the solutions found so that you don't get repeats.

The loop you had involved the inner loop counting down. It works in almost the same way as the loop above except that y starts at 40 and counts down.

Remember though. This method of finding solutions is quite inefficient. It would probably be a better idea to try something like this:
Code:
```float y;
int x;

for(x = 0; x <= 40; x++)
{
y = sqrt(1600 - (x*x));
if( y - floor(y) == 0 )
{
/* Solution found */
}
}```
Since that way you only have to loop through one variable, not two.

3. thanks for the suggestions, I'll see what I can do with that

4. thanks! This helped alot! It makes alot more sense to have them both start at 0.

5. Originally Posted by aromash
thanks! This helped alot! It makes alot more sense to have them both start at 0.
Given that you are enforcing a constraint of y > x, I'd suggest it doesn't really make much sense for the inner loop (over y) to start at zero every time.