Task: Design and Use Triangle Class – C++ Program

### Detail of C++ Program for Design and Use Triangle Class

Write a C++ Program to design a class Triangle with two float variables ‘base’ and ‘height’ and three member functions

1. void setBase(float b) to set value of base

2. void setHeight(float h) to set value of base

3. float area() to calculate area of triangle

with formula area = 1/2 x base x height.

### Source code

/* Write a C++ Program to design a class Triangle with two float variables 'base' and 'height' and three member functions 1. void setBase(float b) to set value of base 2. void setHeight(float h) to set value of base 3. float area() to calculate area of triangle with formula area = 1/2 x base x height */ #include<iostream> using namespace std; // define a class Temperature class Triangle { private: float base, height; public: void setBase(float b) { base = b; } void setHeight(float h) { height = h; } float area() { float a; a= 1.0 / 2.0 * base * height; return a; } }; int main() { // define an object of Triangle class Triangle triangle1; float b,h; cout<<"Enter base and height of triangle="; cin>>b>>h; // set value of base triangle1.setBase(b); // set value of height triangle1.setHeight(h); // call area() function with object triangle1 cout<<"Area of Triangle="<<triangle1.area(); return 0; }

How this Program works?

- We will define a class Triangle using class keyword.
- Two member variables are base and height of triangle.
- There are two member functions: setBase() and setHeight() to set or change the values of member variables.
- There is a member function to calculate area of triangle, called area() that will return area of the triangle.
- The main function has statements to get two values from the user for base and height.
- There are statements to create an object triangle1 of Triangle class.
- We will set base and height by calling the corresponding memebr functions.
- Then we call the function area() that will calculate and return the area of triangle1 object with given base and height.
- The area is printed using cout.

Output:

Enter base and height of triangle=4.4

6.5

Area of Triangle=14.3

### You may also like:

Compute area of Triangle Input Three Sides

Java Program Area of Triangle by Three Sides