The Area and Perimeter of a Triangle
To calculate the area of a given triangle we will first measure the length of each side of the triangle and then apply Hero's formula:
Exercise: Given A, B, and C, write a program that computes the perimeter and area of the triangle.
Solution: Since we know A, B, and C, the calculation is straightforward. The perimeter is computed using P = A + B + C. Then, the half-perimeter is calculated, and Hero's formula is applied. In the program shown in Figure 4.1, P first represents the perimeter and then the half-perimeter. A sample run is provided in Figure 4.2.
10 PRINT "THE LENGTHS OF "; 12 PRINT "THE SIDES OF A" 15 PRINT "TRIANGLE "; 20 INPUT A,B,C 30 P=A+B+C
40 PRINT "PERIMETER = ";P 45 PRINT 50 P=0.5*P
60 S=SQR(P*(P-A)*(P-B)*(P-C)) 70 PRINT "AREA = ";S 80 END
— Figure 4.1: Program for Computing the Area of a Triangle
THE LENGTHS OF THE SIDES OF A TRIANGLE ?4,5,7 PERIMETER = 16
AREA = 9.79795897
where A, B, and C are the lengths of the three sides and
Comments: To learn more about the conventions of BASIC, let us take a closer look at the program in Figure 4.1:
Line 10: A semicolon or comma placed at the end of the line supresses the automatic carriage return and line-feed, allowing the input to be typed on the same line.
Line 40: PRINT "PERIMETER = ";R In this case, the semicolon is used to cause the numerical value of P to print out immediately next to the space following the equal sign.
Line 45: A PRINT instruction with no parameters produces a blank line. This practice avoids overcrowded or cramped printouts.
Line 50: After the value of the perimeter has been printed, P is no longer needed, thus, it can be used to store the half-perimeter needed forthe next calculation.
Criticism of this program: If the lengths given for A, B, and C in the program shown in Figure 4.1 are not valid lengths for the sides of a triangle (for example, if the sides given were 10, 20 and 40), there would be no way for the computer to indicate this error. Instead, the program would attempt to find the square root of a negative number, which, in general, would be detected by the computer in some inconvenient way.
To remedy this problem, we need to insert a validity check: the length of the longest side should not exceed the sum of the lengths of the two other sides. A test for this condition could be added, or, more directly, we might check that:
Figure 4.3 shows the program in Figure 4.1 after such a test has been added.
A sample run appears in Figure 4.4.
10 PRINT "THE LENGTHS OF THE ";
15 PRINT "SIDES OF A"
18 PRINT "TRIANGLE ";
20 INPUT A,B,C
40 PRINT "PERIMETER = ";P
45 PRINT
57 PRINT "IMPOSSIBLE SET OF";
58 PRINT " SIDES"
59 GO TO 80
60 S=SQR(P*(P-A)*(P-B)*(P-C)) 70 PRINT "AREA = ";S
80 END
— Figure 4.3: Program with Data Validity Check
THE LENGTHS OF THE SIDES OF A TRIANGLE 710,20,40 PERIMETER = 70
Post a comment