Write a C++ program to find out the area of the rectangle and triangle using hierarchical inheritance.




Program Algorithm:
Step 1: Include the header files
Step 2: Declare the base class polygon.
Step 3: Declare and define the function input () to get the width and height.
Step 4: Declare the two derived classes rectangle and triangle.
Step 5: Calculate the area using width and height.
Step 6: Create objects for the derived classes.
Step 7: Declare the derived class object, call the functions input () and calculate the area.




Program Code in C++:
#include<iostream.h>
#include<conio.h>
class polygon
{
protected:
int width, height;
public:
void input(int x, int y)
{
width = x;
height = y;
}
};
class rectangle : public polygon
{
public:
int areaR ()
{
return (width * height);
}
};
class triangle : public polygon
{
public:
int areaT ()
{
return (width * height / 2);
}
};
void main ()
clrscr();
rectangle rect;
triangle tri;
rect.input(6,8);
tri.input(6,10);
cout <<"Area of Rectangle: "<<rect.areaR()<< endl;
cout <<"Area of Triangle: "<<tri.areaT()<< endl;
getch();
}





Program Output:
Area of Rectangle: 48
Area of triangle: 30
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: