CHAPTER 5
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");
for(int i=0; i<50; i++){ // Side A loop
a += 1;
checkHypotenuse(a, b, h);
for(int j=0; j<50; j++){ // Side B loop
b += 1;
checkHypotenuse(a, b, h);
for(int k=0; k<50; k++){ // Hypotenuse loop
h += 1;
checkHypotenuse(a, b, h);
}
h = 0; // reset h after Hypotenuse loop ends
}
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;
public static void main(String[] args){
double infiniteSeries = 0.0f;
boolean sign = true;
long count = 0;
System.out.print("The first 20 terms of the infinite series\n");
System.out.printf("%-10s %-10s\n","TERMS","VALUE");
//Since we wanted to discard even values of i,
//for loop will only execute half of the total iteration.
//So we need to multiply TERMS with 2 to loop until the actual iteration count
long totalIterationCount = TERMS * 2;
for(int i=1; i<= totalIterationCount; i+=2){
// only compute odd numbers
if(i % 2 == 0)
continue; // skip the iteration if it is even
// check if addition or subtraction
if(sign)
infiniteSeries += (4.0 / (double)i);
else
infiniteSeries -= (4.0 / (double)i);
count += 1;
System.out.printf("%-10d %-10f\n",count,infiniteSeries);
// reverse the sign after every iteration
sign = !sign;
}
}
}
Output:
The first 20 terms of the infinite series
TERMS VALUE
1 4.000000
2 2.666667
3 3.466667
.
.
20 3.091624