C program to find the areas of geometrical figures using switch case

CServer Side ProgrammingProgramming

Problem

Find the areas of rectangle, square, triangle, circle by using the switch case statement, User need to enter base, height, side, radius, breadth and length at runtime to calculate the areas of all geometrical figures.

Solution

The solution to find the areas of rectangle, square, triangle, circle by using the switch case statement is explained below −

Formulae

The formulae for finding the areas of the respective geometrical figures are as follows −

  • Area of rectangle = breadth *length;
  • Area of square = side * side;
  • Area of circle = 3.142*radius*radius;
  • Area of triangle = 0.5 *base*height;

Example

Following is the C program to find the areas of rectangle, square, triangle, circle by using the switch case statement

 Live Demo

#include <stdio.h>
void main(){
   int fig_code;
   float side, base, length, breadth, height, area, radius;
   printf("-------------------------\n");
   printf(" 1 --> Circle\n");
   printf(" 2 --> Rectangle\n");
   printf(" 3 --> Triangle\n");
   printf(" 4 --> Square\n");
   printf("-------------------------\n");
   printf("Enter the Figure code\n");
   scanf("%d", &fig_code);
   switch(fig_code){
      case 1:
         printf(" Enter the radius\n");
         scanf("%f",&radius);
         area=3.142*radius*radius;
         printf("Area of a circle=%f\n", area);
         break;
      case 2:
         printf(" Enter the breadth and length\n");
         scanf("%f %f",&breadth, &length);
         area=breadth *length;
         printf("Area of a Rectangle=%f\n", area);
         break;
      case 3:
         printf(" Enter the base and height\n");
         scanf("%f %f", &base, &height);
         area=0.5 *base*height;
         printf("Area of a Triangle=%f\n", area);
         break;
      case 4:
         printf(" Enter the side\n");
         scanf("%f", &side);
         area=side * side;
         printf("Area of a Square=%f\n", area);
         break;
      default:
      printf(" Error in figure code\n");
      break;
   }
}

Output

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

Run 1:
-------------------------
1 --> Circle
2 --> Rectangle
3 --> Triangle
4 --> Square
-------------------------
Enter the Figure code
3
Enter the base and height
4
7

Area of a Triangle=14.000000

Run 2:
-------------------------
1 --> Circle
2 --> Rectangle
3 --> Triangle
4 --> Square
-------------------------
Enter the Figure code
1
Enter the radius
8
Area of a circle=201.087997
raja
Published on 01-Sep-2021 12:59:38
Advertisements