Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program to define a class to represent triangle. Data members should inc

ID: 3692611 • Letter: W

Question

Write a program to define a class to represent triangle. Data members should include base, height, area of type float. The data members base and height must have private access. The data member area must have public access. Member functions should allow the following: A constructor to initialize its data members i.e base and height A function to calculate area of the triangle(formula: 1/2 * base * height) The member functions of class triangle must have public access. In the main function do the following: Create a triangle object trl. Initialize the data members through a constructor. The values for base and height are 2.0, 5.2. Calculate area of triangle and print the value of area to the console. Create another triangle object tr2. Initialize the data members through a constructor. The values for base and height are 5.8, 2.2. Calculate area of triangle and print the value of area to the console.

Explanation / Answer

/*** Triangle.h ***/

#ifndef TRIANGLE_H
#define TRIANGLE_H

class Triangle
{

   private:
       float base, height;

   public:
       Triangle(float base, float height);
       float get_area();

};

#endif

/*** Triangle.cpp ***/

#include <iostream>
#include "Triangle.h"

using namespace std;


Triangle::Triangle(float Base, float Height){
   base = Base;
   height = Height;
}

float Triangle::get_area(){
   return (0.5*base*height);
}

/*** main.cpp***/

#include <iostream>
#include "Triangle.h"

using namespace std;


int main(){

Triangle tr1(2.0, 5.2);
Triangle tr2(5.8, 2.2);


cout << "The area of the triangle tr1 is " << tr1.get_area() << ' ';
cout << "The area of the triangle tr2 is " << tr2.get_area() << ' ';

return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote