- Back to Home »
- Assignments »
- CS201 ASSIGNMENT NO 4 Fall 2012 FULL SOLUTION
Posted by : Anonymous
Friday, 25 January 2013
Problem Statement: You
are required to write a program for calculating area of Trapezoid. Formula for calculating area of trapezoid is
Where
a and b are two bases of trapezoid and h corresponds to height.
Detailed Description:
- Create a
class named Trapezoid which contains
two bases and height as data members.
- Implement a
default constructor to initialize all data members with zero and a
parameterized constructor which takes three arguments to initialize data
members of class.
- Take input
from user for base1, base2 and height of 2 objects.
- Overload +
operator for the class Trapezoid
in such a way that corresponding elements of both objects of the same
class can be added.
- Also implement a friend function named calculateArea()
which takes two objects of the class Trapezoid as arguments, adds both
objects using overloaded + operator and calculates the area of resultant Trapezoid
object.
Solution:
#include <iostream>
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
using namespace std;
class trapezoid{
public:
trapezoid();
trapezoid(float,float,float);
trapezoid operator +(trapezoid&);
void getinput();
void set_base1(float);
void set_base2(float);
void set_hight(float);
void display();
friend void calculateArea(trapezoid,trapezoid);
private:
float base1,base2,hight;
};
trapezoid::trapezoid()
{
base1 = 0.0;
base2 = 0.0;
hight = 0;
}
trapezoid::trapezoid(float bs1,float bs2,float ht)
{
base1 = bs1;
base2 = bs2;
hight = ht;
}
void trapezoid::display()
{
cout<<"base 1: "<<base1<<endl;
cout<<"base 2: "<<base2<<endl;
cout<<"hight : "<<hight<<endl;
cout<<"The Eare of the Trapezoid is: "<<(base1+base2)/2*hight<<endl;
}
void trapezoid::set_base1(float bs1)
{
base1 = bs1;
}
void trapezoid::set_base2(float bs2)
{
base2 = bs2;
}
void trapezoid::set_hight(float ht)
{
hight = ht;
}
trapezoid trapezoid::operator+(trapezoid& trap)
{
trapezoid temp;
temp.base1 = base1 + trap.base1;
temp.base2 = base2 + trap.base2;
temp.hight = hight + trap.hight;
return temp;
}
void trapezoid::getinput()
{
float bs1 = 0.0;
float bs2 = 0.0;
float ht = 0;
cout<<"Please Enter Base 1: ";
cin>>bs1;
cout<<"Please Enter Base 2: ";
cin>>bs2;
cout<<"Please Enter Hight: ";
cin>>ht;
set_base1(bs1);
set_base2(bs2);
set_hight(ht);
}
void calculateArea(trapezoid bs1,trapezoid bs2)
{
trapezoid temp;
temp = bs1 + bs2;
temp.display();
}
int main()
{
trapezoid bs1;
trapezoid bs2;
cout<<"Object {1}"<<endl;
bs1.getinput();
cout<<endl;
cout<<"Object {2}"<<endl;
bs2.getinput();
calculateArea(bs1,bs2);
_getch();
}