Open In App

Program to find the area of different shapes | Menu Driven

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Write a Menu-driven program to calculate the area of different shapes based on the user choice.

Menu to calculate area of different shapes:

Enter 1 to calculate the area of a circle.
Enter 2 to calculate the area of a triangle.
Enter 3 to calculate the area of a square.
Enter 4 to calculate the area of a rectangle.
Enter 5 to terminate the program.

Formulae for area of different shapes:

Area of a circle = 3.14159265358979323846 * radius * radius
Area of a triangle = (1/2) * base * height
Area of a square = side * side
Area of a rectangle = length * breadth

Approach: To solve the problem, follow the below idea:

The approach is to use Switch-case to make different cases for different choices. The switch case should run until the user enters 5 to terminate the program. Use break statement to avoid fall-through between cases.

Below is the implementation of the approach:

C++




#include <iostream>
using namespace std;
 
// function to return area of a circle
double getCircleArea(double radius)
{
    return (3.14159265358979323846 * radius * radius);
}
 
// function to return area of a triangle
double getTriangleArea(double base, double height)
{
    return (base * height * 0.5);
}
 
// function to return area of a square
double getSquareArea(double side) { return side * side; }
 
// function to return area of a rectangle
double getRectangleArea(double length, double breadth)
{
    return length * breadth;
}
 
int main()
{
    bool flag = true;
    while (flag) {
        cout << "Enter 1 to calculate the area of a circle"
             << endl;
        cout
            << "Enter 2 to calculate the area of a triangle"
            << endl;
        cout << "Enter 3 to calculate the area of a square"
             << endl;
        cout << "Enter 4 to calculate the area of a "
                "rectangle"
             << endl;
        cout << "Enter 5 to terminate the program" << endl;
        int choice;
        cin >> choice;
        switch (choice) {
        case 1:
            cout << "Enter radius: ";
            double radius;
            cin >> radius;
            cout << "Area = " << getCircleArea(radius)
                 << endl;
            break;
        case 2:
            cout << "Enter base: ";
            double base, height;
            cin >> base;
            cout << "Enter height: ";
            cin >> height;
            cout << "Area = "
                 << getTriangleArea(base, height) << endl;
            break;
        case 3:
            cout << "Enter side length: ";
            double side;
            cin >> side;
            cout << "Area = " << getSquareArea(side)
                 << endl;
            break;
        case 4:
            cout << "Enter length: ";
            double length, breadth;
            cin >> length;
            cout << "Enter breadth: ";
            cin >> breadth;
            cout << "Area = "
                 << getRectangleArea(length, breadth)
                 << endl;
            break;
        case 5:
            flag = false;
            break;
        default:
            cout << "Invalid Choice" << endl;
        }
    }
    cout << "Program terminated" << endl;
    return 0;
}


Java




import java.util.Scanner;
 
public class AreaCalculator {
    // function to return area of a circle
    static double getCircleArea(double radius) {
        return Math.PI * radius * radius;
    }
 
    // function to return area of a triangle
    static double getTriangleArea(double base, double height) {
        return base * height * 0.5;
    }
 
    // function to return area of a square
    static double getSquareArea(double side) {
        return side * side;
    }
 
    // function to return area of a rectangle
    static double getRectangleArea(double length, double breadth) {
        return length * breadth;
    }
 
    public static void main(String[] args) {
        boolean flag = true;
        Scanner scanner = new Scanner(System.in);
 
        while (flag) {
            try {
                System.out.println("Enter 1 to calculate the area of a circle");
                System.out.println("Enter 2 to calculate the area of a triangle");
                System.out.println("Enter 3 to calculate the area of a square");
                System.out.println("Enter 4 to calculate the area of a rectangle");
                System.out.println("Enter 5 to terminate the program");
 
                int choice = scanner.nextInt();
 
                switch (choice) {
                    case 1:
                        System.out.print("Enter radius: ");
                        double radius = scanner.nextDouble();
                        System.out.println("Area = " + getCircleArea(radius));
                        break;
                    case 2:
                        System.out.print("Enter base: ");
                        double base = scanner.nextDouble();
                        System.out.print("Enter height: ");
                        double height = scanner.nextDouble();
                        System.out.println("Area = " + getTriangleArea(base, height));
                        break;
                    case 3:
                        System.out.print("Enter side length: ");
                        double side = scanner.nextDouble();
                        System.out.println("Area = " + getSquareArea(side));
                        break;
                    case 4:
                        System.out.print("Enter length: ");
                        double length = scanner.nextDouble();
                        System.out.print("Enter breadth: ");
                        double breadth = scanner.nextDouble();
                        System.out.println("Area = " + getRectangleArea(length, breadth));
                        break;
                    case 5:
                        flag = false;
                        break;
                    default:
                        System.out.println("Invalid Choice");
                }
            } catch (java.util.NoSuchElementException e) {
                System.out.println("No input provided. Exiting...");
                break;
            }
        }
 
        System.out.println("Program terminated");
        scanner.close();
    }
}


Python3




import math
 
# Function to return area of a circle
def get_circle_area(radius):
    return math.pi * radius**2
 
# Function to return area of a triangle
def get_triangle_area(base, height):
    return 0.5 * base * height
 
# Function to return area of a square
def get_square_area(side):
    return side**2
 
# Function to return area of a rectangle
def get_rectangle_area(length, breadth):
    return length * breadth
 
# Main program
flag = True
while flag:
    print("Enter 1 to calculate the area of a circle")
    print("Enter 2 to calculate the area of a triangle")
    print("Enter 3 to calculate the area of a square")
    print("Enter 4 to calculate the area of a rectangle")
    print("Enter 5 to terminate the program")
 
    choice = int(input("Enter your choice: "))
 
    if choice == 1:
        radius = float(input("Enter radius: "))
        print("Area =", get_circle_area(radius))
    elif choice == 2:
        base = float(input("Enter base: "))
        height = float(input("Enter height: "))
        print("Area =", get_triangle_area(base, height))
    elif choice == 3:
        side = float(input("Enter side length: "))
        print("Area =", get_square_area(side))
    elif choice == 4:
        length = float(input("Enter length: "))
        breadth = float(input("Enter breadth: "))
        print("Area =", get_rectangle_area(length, breadth))
    elif choice == 5:
        flag = False
    else:
        print("Invalid Choice")
 
print("Program terminated")


C#




using System;
 
public class Scanner : IDisposable
{
    private readonly System.IO.TextReader _reader;
    private string _inputBuffer = string.Empty;
 
    public Scanner(System.IO.TextReader reader = null)
    {
        _reader = reader ?? Console.In;
    }
 
    public void Dispose()
    {
        _reader.Dispose();
    }
 
    public int NextInt()
    {
        return int.Parse(Next());
    }
 
    public double NextDouble()
    {
        return double.Parse(Next());
    }
 
    private string Next()
    {
        if (string.IsNullOrEmpty(_inputBuffer))
        {
            _inputBuffer = _reader.ReadLine();
            if (_inputBuffer == null)
            {
                throw new InvalidOperationException("Not enough input.");
            }
        }
        var tokens = _inputBuffer.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
        if (tokens.Length == 0)
        {
            throw new InvalidOperationException("Not enough input.");
        }
        _inputBuffer = string.Empty;
        return tokens[0];
    }
 
    public void ClearBuffer()
    {
        _inputBuffer = string.Empty;
    }
}
 
public class AreaCalculator
{
    // function to return area of a circle
    static double GetCircleArea(double radius)
    {
        return Math.PI * radius * radius;
    }
 
    // function to return area of a triangle
    static double GetTriangleArea(double baseLength, double height)
    {
        return baseLength * height * 0.5;
    }
 
    // function to return area of a square
    static double GetSquareArea(double side)
    {
        return side * side;
    }
 
    // function to return area of a rectangle
    static double GetRectangleArea(double length, double breadth)
    {
        return length * breadth;
    }
 
    public static void Main(string[] args)
    {
        bool flag = true;
        Scanner scanner = new Scanner();
 
        while (flag)
        {
            try
            {
                Console.WriteLine("Enter 1 to calculate the area of a circle");
                Console.WriteLine("Enter 2 to calculate the area of a triangle");
                Console.WriteLine("Enter 3 to calculate the area of a square");
                Console.WriteLine("Enter 4 to calculate the area of a rectangle");
                Console.WriteLine("Enter 5 to terminate the program");
 
                int choice = scanner.NextInt();
 
                switch (choice)
                {
                    case 1:
                        Console.Write("Enter radius: ");
                        double radius = scanner.NextDouble();
                        Console.WriteLine("Area = " + GetCircleArea(radius));
                        break;
                    case 2:
                        Console.Write("Enter base: ");
                        double baseLength = scanner.NextDouble();
                        Console.Write("Enter height: ");
                        double height = scanner.NextDouble();
                        Console.WriteLine("Area = " + GetTriangleArea(baseLength, height));
                        break;
                    case 3:
                        Console.Write("Enter side length: ");
                        double side = scanner.NextDouble();
                        Console.WriteLine("Area = " + GetSquareArea(side));
                        break;
                    case 4:
                        Console.Write("Enter length: ");
                        double length = scanner.NextDouble();
                        Console.Write("Enter breadth: ");
                        double breadth = scanner.NextDouble();
                        Console.WriteLine("Area = " + GetRectangleArea(length, breadth));
                        break;
                    case 5:
                        flag = false;
                        break;
                    default:
                        Console.WriteLine("Invalid Choice");
                        break;
                }
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.Message);
                break;
            }
        }
 
        Console.WriteLine("Program terminated");
    }
}


Javascript




// Function to return area of a circle
function getCircleArea(radius) {
    return Math.PI * Math.pow(radius, 2);
}
 
// Function to return area of a triangle
function getTriangleArea(base, height) {
    return 0.5 * base * height;
}
 
// Function to return area of a square
function getSquareArea(side) {
    return Math.pow(side, 2);
}
 
// Function to return area of a rectangle
function getRectangleArea(length, breadth) {
    return length * breadth;
}
 
// Main program
let flag = true;
while (flag) {
    console.log("Enter 1 to calculate the area of a circle");
    console.log("Enter 2 to calculate the area of a triangle");
    console.log("Enter 3 to calculate the area of a square");
    console.log("Enter 4 to calculate the area of a rectangle");
    console.log("Enter 5 to terminate the program");
 
    let choice = prompt("Enter your choice: ");
 
    if (choice == 1) {
        let radius = parseFloat(prompt("Enter radius: "));
        console.log("Area =", getCircleArea(radius));
    } else if (choice == 2) {
        let base = parseFloat(prompt("Enter base: "));
        let height = parseFloat(prompt("Enter height: "));
        console.log("Area =", getTriangleArea(base, height));
    } else if (choice == 3) {
        let side = parseFloat(prompt("Enter side length: "));
        console.log("Area =", getSquareArea(side));
    } else if (choice == 4) {
        let length = parseFloat(prompt("Enter length: "));
        let breadth = parseFloat(prompt("Enter breadth: "));
        console.log("Area =", getRectangleArea(length, breadth));
    } else if (choice == 5) {
        flag = false;
    } else {
        console.log("Invalid Choice");
    }
}
 
console.log("Program terminated");


Output:

Enter 1 to calculate the area of a circle
Enter 2 to calculate the area of a triangle
Enter 3 to calculate the area of a square
Enter 4 to calculate the area of a rectangle
Enter 5 to terminate the program
1
Enter radius: 14
Area = 615.752
Enter 1 to calculate the area of a circle
Enter 2 to calculate the area of a triangle
Enter 3 to calculate the area of a square
Enter 4 to calculate the area of a rectangle
Enter 5 to terminate the program
2
Enter base: 10
Enter height: 20
Area = 100
Enter 1 to calculate the area of a circle
Enter 2 to calculate the area of a triangle
Enter 3 to calculate the area of a square
Enter 4 to calculate the area of a rectangle
Enter 5 to terminate the program
3
Enter side length: 10
Area = 100
Enter 1 to calculate the area of a circle
Enter 2 to calculate the area of a triangle
Enter 3 to calculate the area of a square
Enter 4 to calculate the area of a rectangle
Enter 5 to terminate the program
4
Enter length: 5
Enter breadth: 10
Area = 50
Enter 1 to calculate the area of a circle
Enter 2 to calculate the area of a triangle
Enter 3 to calculate the area of a square
Enter 4 to calculate the area of a rectangle
Enter 5 to terminate the program
9
Invalid Choice
Enter 1 to calculate the area of a circle
Enter 2 to calculate the area of a triangle
Enter 3 to calculate the area of a square
Enter 4 to calculate the area of a rectangle
Enter 5 to terminate the program
5
Program terminated

Time Complexity: O(1)
Auxiliary Space: O(1)



Similar Reads

Program to check if a person can vote using his age | Menu-Driven
Write a Menu-driven program to check the eligibility of a person to vote or not.Eligibility to vote: The age of the person should be greater than or equal to 18. A menu-driven program is a type of computer program that allows users to interact with it by selecting options from a menu. Instead of typing commands or code, users navigate through a ser
5 min read
Program to print the name of month using the month number | Menu-Driven
Your task is to design a menu-driven program that asks the user to input a month number, and the program prints the name of the month. A menu-driven program is a type of computer program that allows users to interact with it by selecting options from a menu. Instead of typing commands or code, users navigate through a series of menus that present a
7 min read
Program to check if a student passes/fails using his grade | Menu Driven
Write a Menu-driven program to check Whether a student passes/fails using his/her grade.Condition to pass: Grade should be greater than or equal to 33.Valid grade range: 0 to 100 A menu-driven program is a type of computer program that allows users to interact with it by selecting options from a menu. Instead of typing commands or code, users navig
6 min read
Getting Started with Menu Driven Programs in Programming
Have you ever used a menu to choose options on a computer or a phone? Menu-driven programs in programming work similarly. They offer users a menu of choices to select from, making it easy to interact with the program. In this article, we will start from the basics of creating menu-driven programs, suitable for beginners and experienced programmers
3 min read
Program to find the side length of a square given its area
Write a program to find the side length of a square with given area. Examples: Input: Area = 16 square units Output: Side length = 4 units Input: Area = 25 square meters Output: Side length = 5 meters Approach: To solve the problem, follow the below idea: The side length of a square can be calculated using the formula: Side length=sqrt(Area)‚Äč. Step
2 min read
Program to find the perimeter of a square given its area
Write a program to find the perimeter of a square given its area. Examples: Input: Area = 36 square unitsOutput: Perimeter = 24 unitsExplanation: Since the area of the square is 36 square units, so the side of square will be 6 units. Therefore, the perimeter of the square will be 4 * 6 = 24 units. Input: Area = 25 square unitsOutput: Perimeter = 20
3 min read
Different types of Coding Schemes to represent data
Any text-based data is stored by the computer in the form of bits(a series of 1s and 0s), and follows the specified Coding Scheme. The coding scheme is a Standard that tells the user's machine which character represents which set of bytes. Specifying the coding scheme used is very important as without it, the machine could interpret the given bytes
3 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
Program to find Minkowski Distance
Given two arrays A[] and B[] as position vector of two points in n-dimensional space along with an integer p, the task is to calculate Minkowski Distance between these two points. The Minkowski distance is a generalization of other distance measures, such as Euclidean and Manhattan distances, and is defined as: [Tex]D(A, B) = \left( \sum_{i=1}^{n}
4 min read
Program to find the sum and difference of two numbers
Given two Integers A and B, your task is to find the sum and difference of two numbers. Examples: Input: A = 4, B = 9Output: Sum = 13 and Difference = -5Input: A = -3, B = -2Output: Sum = -5 and Difference = -1 Approach: The problem can be solved using arithmetic operators. Operations on Numbers: Addition (+): This operation is used to add the inpu
3 min read
Article Tags :