I am learning Java using “Java how to program” (Deitel and Deitel).
Right now I´m stuck solving an exercise that wants me to print out a table with all possible values of “pythagoran tripples” under 500. I am supposed to use a nested “for-loop” to check all possibilities. In other words: a, b, and c has to be integers. The following expression has to be true: a2 + b2 = c2, and the program should print a table with all possible combinations ( with c < 500 ). I just can´t figure this out. Can anyone please help me?
My code, which only prints out the first combination ( 3 4 5 ) is as follows:
public class Pythagoras
{
public static void main(String[] args)
{
for (int a = 3, b = 4, c = 5; (Math.pow(a, 2) + Math.pow(b, 2) == Math.pow(c, 2)) && (c <= 500); c++)
{
System.out.printf("%d %20d %20d", a, b, c);
}
}
}
Your code only prints
3 4 5because it only runs 1 iteration of theforloop.In your for loop, you enlarge c each iteration, but you don’t change a and b.
That means that after the first iteration, it will evaluate
3^2 + 4^2 == 6^2, which returns false and it thus exits theforloop.To solve this, you could use three nested
forloops like this: