I'm just starting to get used to object oriented programming. So I figured one of the easiest ways to practice would be to make a program to find the perimeter and/or area of a triangle.
I was going to add a "do...while loop" to exit, as well as a menu for whether or not you wanted to find the area or perimeter, but I figured that would be a waste of time, because the point was for me to learn about Objects, not deal with loops.
Code:
/* Basic Triangle functions code by Disharmony */
// DisHarm0ny[at]yahoo.com
#include <cstdlib>
#include <iostream>
//defining the class "triangle"
class triangle
{
public:
int getSide1();
int getSide2();
int getSide3();
float getBase();
float getHeight();
void setVars();
private:
float height;
int base;
int side1;
int side2;
int side3;
float area_value;
int perimeter_value;
};
void triangle::setVars()
{
std::cout << "What is the value of side1? \n";
std::cin >> side1;
std::cout << "What is the value of side2? \n";
std::cin >> side2;
std::cout << "What is the value of side3? \n";
std::cin >> side3;
std::cout << "What is the value of base? \n";
std::cin >> base;
std::cout << "What is the height of the triangle? \n";
std::cin >> height;
}
int triangle::getSide1()
{
return side1;
}
int triangle::getSide2()
{
return side2;
}
int triangle::getSide3()
{
return side3;
}
float triangle::getBase()
{
return base;
}
float triangle::getHeight()
{
return height;
}
// Done defining the "triangle" class
float area(float,float);
int perimeter(int ,int ,int );
triangle tri;
using std::cout;
using std::cin;
int main()
{
tri.setVars(); //prompt for variables
int side1=tri.getSide1(); //getting the private member variables from public methods
int side2=tri.getSide2();
int side3= tri.getSide3();
float base = tri.getBase();
float height = tri.getHeight();
int perimeter_value = perimeter(side1, side2, side3);// calculate perimeter and area
float area_value = area(height, base);
cout << "The triangle's perimeter is: " << perimeter_value <<"\n";
cout << "The triangle's area is: " << area_value << "\n";
cout << "------------------------------------\n";
system("PAUSE");
return EXIT_SUCCESS;
}
float area(float height,float base)
{
float result = height*base;
float area_value = result / 2;
return area_value;
}
int perimeter(int one,int two, int three)
{
int perimeter_value;
perimeter_value = one + two + three;
return perimeter_value;
}