C++ Program to Calculate Area of Various Shapes (Circle, Rectangle, Triangle)

1. Introduction

Calculating the area of basic geometric shapes is a fundamental concept in geometry. In this blog post, we will explore a C++ program that allows users to calculate the area of various shapes like circles, rectangles, and triangles.

2. Program Overview

Our program will:

1. Display a menu to the user to choose the shape.

2. Based on the choice, prompt the user for the necessary dimensions.

3. Calculate the area of the chosen shape.

4. Display the calculated area.

3. Code Program

#include<iostream>
#include<cmath> // For using M_PI for value of pi
using namespace std;

int main() {
    int choice;
    float area;

    cout << "Choose a shape:" << endl;
    cout << "1. Circle" << endl;
    cout << "2. Rectangle" << endl;
    cout << "3. Triangle" << endl;
    cin >> choice;

    switch(choice) {
        case 1: {
            float radius;
            cout << "Enter radius of the circle: ";
            cin >> radius;
            area = M_PI * radius * radius;
            cout << "Area of the circle: " << area << endl;
            break;
        }
        case 2: {
            float length, breadth;
            cout << "Enter length and breadth of the rectangle: ";
            cin >> length >> breadth;
            area = length * breadth;
            cout << "Area of the rectangle: " << area << endl;
            break;
        }
        case 3: {
            float base, height;
            cout << "Enter base and height of the triangle: ";
            cin >> base >> height;
            area = 0.5 * base * height;
            cout << "Area of the triangle: " << area << endl;
            break;
        }
        default:
            cout << "Invalid choice!" << endl;
    }

    return 0;
}

Output:

Choose a shape:
1. Circle
2. Rectangle
3. Triangle
1
Enter radius of the circle: 5
Area of the circle: 78.5398

4. Step By Step Explanation

1. The program starts by showing a menu to the user, allowing them to choose between three shapes: circle, rectangle, and triangle.

2. Based on the user's choice, it prompts for the necessary dimensions:

- For circle: radius

- For rectangle: length and breadth

- For triangle: base and height

3. It then calculates the area using the formulas:

- Circle: pi * radius * radius

- Rectangle: length * breadth

- Triangle: 0.5 * base * height

4. Finally, it displays the computed area.

Comments