# C program to print area of triangle, square, circle, rectangle and polygon using switch case.

CServer Side ProgrammingProgramming

## Problem

Write a program to calculate the area of triangle, square, circle, rectangle and polygon by using the switch case.

## Solution

Based on case number, the area of triangle, square, circle, rectangle and polygon is calculated.

• The logic used to find area of triangle is as follows −

Enter sides of a triangle a,b,c

s=(float)(a+b+c)/2;
area=(float)(sqrt(s*(s-a)*(s-b)*(s-c)));
• The logic used to find area of square is as follows −

Enter the side of square at runtime.

area=(float)side*side;
• The logic used to find area of circle is as follows −

Enter the radius of circle at runtime

area=(float)3.14159*radius*radius;
• The logic used to find area of rectangle is as follows −

Enter length and breadth of rectangle at runtime

area=(float)len*breadth;
• The logic used to find area of parallelogram is as follows −

Enter base and height of parallelogram

area=(float)base*height;

## Example

Following is the C program to calculate the area of triangle, square, circle, rectangle and polygon by using the switch case −

#include<stdio.h>
#include<math.h>
main(){
int choice;
printf("Enter\n1 to find area of Triangle\n2 for finding area of Square\n3 for finding area of Circle\n4 for finding area of Rectangle\n5 for Parallelogram\n");
scanf("%d",&choice);
switch(choice) {
case 1: {
int a,b,c;
float s,area;
printf("Enter sides of triangle\n");
scanf("%d%d %d",&a,&b,&c);
s=(float)(a+b+c)/2;
area=(float)(sqrt(s*(s-a)*(s-b)*(s-c)));
printf("Area of Triangle is %f\n",area);
break;
}
case 2: {
float side,area;
printf("Enter Sides of Square\n");
scanf("%f",&side);
area=(float)side*side;
printf("Area of Square is %f\n",area);
break;
}
case 3: {
printf("Enter Radius of Circle\n");
printf("Area of Circle %f\n",area);
break;
}
case 4: {
printf("Enter Length and Breadth of Rectangle\n");
printf("Area of Rectangle is %f\n",area);
break;
}
case 5: {
float base,height,area;
printf("Enter base and height of Parallelogram\n");
scanf("%f %f",&base,&height);
area=(float)base*height;
printf("Enter area of Parallelogram is %f\n",area);
break;
}
default: {
printf("Invalid Choice\n");
break;
}
}
}

## Output

When the above program is executed, it produces the following output −

When the above program is executed, it produces the following output:
Run 1:
1 to find area of Triangle
2 for finding area of Square
3 for finding area of Circle
4 for finding area of Rectangle
5 for Parallelogram
5
Enter base and height of Parallelogram
2 4 6 8
Enter area of Parallelogram is 8.000000
Run 2:
1 to find area of Triangle
2 for finding area of Square
3 for finding area of Circle
4 for finding area of Rectangle
5 for Parallelogram
3
Enter Radius of Circle
4.5
Area of Circle is 63.617199
Published on 25-Mar-2021 07:32:32