C++ Program to Find the Area of Shapes using Switch Case

This C++ program computes area of a shape using switch case. The program takes shape as an input and identifies the shape using a switch case. The statements then takes required values as input, computes the area and prints it.

Here is the source code of the C++ program computes area of a shape using switch case. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Find Area of Shapes using Switch Case
  3.  */ 
  4. #include <iostream>
  5. const float PI = 3.14;
  6.  
  7. void calculateArea(std::string shape)
  8. {
  9.     /* Comparing first character of shape string */
  10.     switch (shape[0]) {
  11.     case 'c':
  12.  
  13.         float r;
  14.  
  15.         std::cout << "\nEnter the radius ";
  16.         std::cin >> r;
  17.         std::cout << "\nArea of Circle : " << PI * r * r
  18.                   << " square units" << std::endl;
  19.         break;
  20.     case 's':
  21.         float a;
  22.  
  23.         std::cout << "\nEnter the side length ";
  24.         std::cin >> a;
  25.         std::cout << "\nArea of Square : " << a * a
  26.                   << " square units" << std::endl;
  27.         break;
  28.  
  29.     case 'r':
  30.         float b, h;
  31.  
  32.         std::cout << "\nEnter the breadth ";
  33.         std::cin >> b;
  34.         std::cout << "\nEnter the height ";
  35.         std::cin >> h;
  36.         std::cout << "\nArea of Rectangle : " << b * h
  37.                   << " square units" << std::endl;
  38.         break;
  39.     }
  40. }
  41.  
  42. int main()
  43. {
  44.     std::string s;
  45.  
  46.     std::cout << "Enter the shape : ";
  47.     getline(std::cin, s);
  48.     calculateArea(s);
  49. }

$ a.out
Enter the shape : rectangle
Enter the breadth 20
Enter the height 40
Area of Rectangle : 800 square units
C:\MinGW\bin>a.exe
Enter the shape : circle
Enter the radius 10
Area of Circle : 314 square units

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.