In: Computer Science
1. Write a Python program that will ask the user length and width of the right triangle and find the area of the right-angled triangle. The formula for finding the area of a right-angle triangle is
ab/2. Also, find out the result if you calculate as (ab)/2. Is it the same? If it is same, why it is the same. If it is not the same, why it is not the same.
CODE FOR THE FOLLOWING PROGRAM:-
#length to store length and width to store width of triangle
length=int(input("Enter the length of the right triangle: "));
width=int(input("Enter the width of the right triangle: "));
#Calculating area
#a*b/2 - Here a is length and b is width
area=length*width/2;
#printing the output
print("The area of the triangle is: "+ str(area))
REASON FOR SAME RESULT:- a*b/2 and (a*b)/2 will generate the same result it is because in first case i.e a*b/2 because of the same precedence of multiplication and divison operator's associativity(the order of operators in which they will be evaluated) of the operators will be used to determine the result. In python most of the operators follow left to right associativity. Therefore, first multiplication will take place i.e first a*b will be evaluated and then it will be divided by 2. However, in second case i.e (a*b)/2 here the precedence of the parentheses() is greater than divison /. Therefore, first the operands and operator inside the parentheses will be evaluated which is (a*b) and then it will be divided by 2.
Hence , both will give the same result because in both cases first multiplication is done and then divison i.e the expression is evaluated in the same way though the reasons for evaluation is different in both cases.
SCREENSHOT OF THE CODE AND SAMPLE OUTPUT:-
When result is calculated as ab/2:-
When result is calculated as (ab)/2:-
HAPPY LEARNING