In: Computer Science
Part 2
Write a C code to create a user defined function called RecArea that will calculate the area of a rectangle. Call the function to print the area of the rectangle on the screen.
Note: The user will enter the length and width of a rectangle (decimal values, float) and you
Part 3 (Continue on part 2)
Create another user defined function called TriArea that will calculate the area of a triangle. Print the area of the rectangle on the screen. Area of a triangle is given by:
Note: The user will enter the height and base of the triangle (decimal values or float)
Part 4 (Continue on part 3)
Sum up the two areas found in parts 2 and 3 and display the result to the user.
The code for given problem statement:
#include<stdio.h>
float RecArea(float l,float w) // Calculates area of rectangle, prints the area and return it
{
float area=l*w; // Area of rectangle= length*width
printf("Area of the given rectangle= %f\n",area);
return area;
}
float TriArea(float b,float h) // Calculates area of triangle, prints the area and return it
{
float area=0.5*b*h; // Area of triangle= 1/2*base*height
printf("Area of the given triangle= %f\n",area);
return area;
}
int main()
{
float length,width,height,base,R_Area,T_Area,Total; // Declaration of float variables
printf("Enter value of length and width of rectangle: \n");
printf("length= ");
scanf("%f",&length);
printf("width= ");
scanf("%f",&width);
R_Area=RecArea(length,width); // Calls the RecArea function
printf("Enter value of base and height of triangle: \n");
printf("base= ");
scanf("%f",&base);
printf("height= ");
scanf("%f",&height);
T_Area=TriArea(base,height); // Calls the TriArea function
Total=R_Area+T_Area; // Adding area of rectangle and triangle
printf("Total area is= %f\n",Total);
return 0;
}
The screenshot of the code:
Test
running of the program:
Logic
of the code:
While taking the values into variables the format specifier used is %f for float values. Once user inputs values of length and width, those values are passed to funcion RecArea to calculate return and print the area. Area is returned to the calling function so that it can be used to find total of areas.
Similar process is done for TriArea using base and height.
Variable Total is used to store addition of area of rectangle and triangle. Which is printed at the end.
The formulas used:
Area of rectangle= length x width
Area of triangle=(1/2) x base x height
Float variabes used:
length | To store length of rectangle |
width | To store width of rectangle |
base | To store base of triangle |
height | To store height of triangle |
R_Area | To store area of rectangle |
T_Area | To store area of triangle |
Total | To store sum of area of rectangle and area of triangle |