C++ Online Compiler
Example: Geometry Calculator using Switch Case in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Geometry Calculator using Switch Case #include <iostream> #include <cmath> // Required for M_PI and pow() // Define PI if M_PI is not consistently available or for custom precision #ifndef M_PI #define M_PI 3.14159265358979323846 #endif using namespace std; int main() { int choice; double radius, length, width, base, height; // Step 1: Display a welcome message and the main menu cout << "Welcome to the Geometry Calculator!" << endl; do { cout << "\n-------------------------------------" << endl; cout << "Select a shape to calculate properties:" << endl; cout << "1. Circle" << endl; cout << "2. Rectangle" << endl; cout << "3. Triangle (Area only)" << endl; cout << "4. Exit" << endl; cout << "Enter your choice (1-4): "; cin >> choice; // Step 2: Use a switch statement to handle user's choice switch (choice) { case 1: // Circle cout << "\nEnter radius of the circle: "; cin >> radius; if (radius < 0) { cout << "Radius cannot be negative. Please try again." << endl; break; } cout << "Area of Circle: " << M_PI * radius * radius << endl; cout << "Circumference of Circle: " << 2 * M_PI * radius << endl; break; case 2: // Rectangle cout << "\nEnter length of the rectangle: "; cin >> length; cout << "Enter width of the rectangle: "; cin >> width; if (length < 0 || width < 0) { cout << "Length and width cannot be negative. Please try again." << endl; break; } cout << "Area of Rectangle: " << length * width << endl; cout << "Perimeter of Rectangle: " << 2 * (length + width) << endl; break; case 3: // Triangle (Area only for simplicity) cout << "\nEnter base of the triangle: "; cin >> base; cout << "Enter height of the triangle: "; cin >> height; if (base < 0 || height < 0) { cout << "Base and height cannot be negative. Please try again." << endl; break; } cout << "Area of Triangle: " << 0.5 * base * height << endl; // Perimeter requires three sides, which adds complexity for a simple example. // For now, we focus on area using base and height. break; case 4: // Exit cout << "\nExiting Geometry Calculator. Goodbye!" << endl; break; default: // Invalid choice cout << "\nInvalid choice. Please enter a number between 1 and 4." << endl; break; } } while (choice != 4); // Step 3: Loop until user chooses to exit return 0; }
Output
Clear
ADVERTISEMENTS