Java_CH5_Exercise
Java_CH5_Exercise
1. The set of three integer values for the lengths of the sides of a right triangle is called a
Pythagorean triple. Write an application that displays a table of the Pythagorean triples for
side1, side2 and the hypotenuse, all no larger than 50. Use a triple-nested for loop that tries
all possibilities.
Program:
package CH_5;
public class PythagorasTriples{
public static void main(String[] args){
int a = 0, b = 0, h = 0;
System.out.print(“Lengths of the three sides that form a right triangle.\n");
System.out.printf("%-10s %-10s %-10s \n","Side A","Side B","Hypotenuse");
}
b = 0; // reset b after Side B loop ends
}
}// main method
public static void checkHypotenuse(int a, int b, int h){ // check Pythagorean theorem
if( (a * a) + (b * b) == (h * h) ) {
System.out.printf("%-10d %-10d %-10d \n",a,b,h);
}
}
}// class end
Output:
Lengths of the three sides that form a right triangle.
Side A Side B Hypotenuse
3 4 5
4 3 5
.
.
.
48 14 50
2. Write a java program that compute and display values of the first 20 terms of the following
infinite series.
4 4 4 4 4
π=4− + − + − +…
3 5 7 9 11
Program:
package CH_5;
public class ValueOfPi{
private static final long TERMS = 20;
count += 1;
System.out.printf("%-10d %-10f\n",count,infiniteSeries);
}
}
}
Output:
The first 20 terms of the infinite series
TERMS VALUE
1 4.000000
2 2.666667
3 3.466667
.
.
20 3.091624