Knowee
Questions
Features
Study Tools

Write a program to calculate the area of circle, triangle, rectangle and square using function overloading.

Question

Write a program to calculate the area of circle, triangle, rectangle and square using function overloading.

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a Python program that uses function overloading to calculate the area of a circle, triangle, rectangle, and square.

In Python, we don't have built-in function overloading. We can achieve similar functionality using optional parameters, or by checking the type of the arguments passed.

import math

def calculate_area(shape, a=None, b=None):
    if shape == 'circle':
        if a is None:
            print("You need to provide the radius for a circle")
            return None
        else:
            return math.pi * a * a
    elif shape == 'triangle':
        if a is None or b is None:
            print("You need to provide the base and height for a triangle")
            return None
        else:
            return 0.5 * a * b
    elif shape == 'rectangle':
        if a is None or b is None:
            print("You need to provide the length and width for a rectangle")
            return None
        else:
            return a * b
    elif shape == 'square':
        if a is None:
            print("You need to provide the side length for a square")
            return None
        else:
            return a * a
    else:
        print("Unknown shape")
        return None

# Test the function
print(calculate_area('circle', a=5))
print(calculate_area('triangle', a=5, b=10))
print(calculate_area('rectangle', a=5, b=10))
print(calculate_area('square', a=5))

In this program, the calculate_area function takes the shape name and the necessary parameters for that shape. It then calculates the area based on the shape. If the necessary parameters are not provided, it prints an error message and returns None.

This problem has been solved

Similar Questions

Write a VB Program that calculates the area of a rectangle give that the area = lengthmultiplied by width.

Write a program to prompt user for an integer and display a triangle of stars with the same height as the input provided by the user. For example:

Find the area of the figure.(Sides meet at right angles.)3in1in2in4in2in1in3in2insquareinches

The diagram below is formed by 4 identical circles and a square. Each circle has a radius of 14 m. What is the area of the unshaded part? Take π as 3.14.

What is the area of a rectangle with vertices at (7, 3), (12, 3), (12, 11), and (7, 11)?A.45 units2B.26 units2C.20 units2D.40 units2

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.