4. Write a Program in C to calculate the area of a triangle, rectangle or a circle using function depending on the choice entered by the user.
1. Triangle 2. Rectangle 3. Circle 4. Exit
Answers
The given problem is solved using language - C.
#include <stdio.h>
void triangleArea(){
float a,b,c;
printf("Enter the first side of the triangle: ");
scanf("%f",&a);
printf("Enter the second side of the triangle: ");
scanf("%f",&b);
printf("Enter the third side of the triangle: ");
scanf("%f",&c);
float s,area;
s=(a+b+c)/2.0;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf("Area of the triangle is %.2f square units.",area);
}
void rectangleArea(){
float a,b;
printf("Enter the length of the rectangle: ");
scanf("%f",&a);
printf("Enter the breadth of the rectangle: ");
scanf("%f",&b);
printf("The area of the rectangle is: %.2f",a*b);
}
void circleArea(){
float r,a;
printf("Enter the radius of the circle: ");
scanf("%f",&r);
a=3.14159*r*r;
printf("The area of the circle is: %.2f",a);
}
int main() {
int c;
printf("1. Area of a triangle.\n");
printf("2. Area of a rectangle.\n");
printf("3. Area of a circle.\n");
printf("4. Exit.\n\n");
printf("Enter your choice: ");
scanf("%d",&c);
switch(c){
case 1:
triangleArea();
break;
case 2:
rectangleArea();
break;
case 3:
circleArea();
break;
case 4:
printf("Program Terminated.");
break;
default: printf("Invalid choice.");
}
return 0;
}
#1
1. Area of a triangle.
2. Area of a rectangle.
3. Area of a circle.
4. Exit.
Enter your choice: 1
Enter the first side of the triangle: 5
Enter the second side of the triangle: 4
Enter the third side of the triangle: 3
Area of the triangle is 6.00 square units.
——————————————————————————
#2
1. Area of a triangle.
2. Area of a rectangle.
3. Area of a circle.
4. Exit.
Enter your choice: 2
Enter the length of the rectangle: 10
Enter the breadth of the rectangle: 5
The area of the rectangle is: 50.00
——————————————————————————
#3
1. Area of a triangle.
2. Area of a rectangle.
3. Area of a circle.
4. Exit.
Enter your choice: 3
Enter the radius of the circle: 5.0
The area of the circle is: 78.54
——————————————————————————
#4
1. Area of a triangle.
2. Area of a rectangle.
3. Area of a circle.
4. Exit.
Enter your choice: 4
Program Terminated.
——————————————————————————
#5
1. Area of a triangle.
2. Area of a rectangle.
3. Area of a circle.
4. Exit.
Enter your choice: 10
Invalid choice.