C++ program to find the third angle of triangle using class

Learn, how can we find the third angle of triangle using the class and object approach?
Submitted by Shubh Pachori, on September 04, 2022

Example:

Input: 
Enter 1st Angle: 35
Enter 2nd Angle: 90

Output: 
Third Angle: 55

C++ code to find the third angle of triangle using the class and object approach

#include <iostream>
using namespace std;

// create a class
class Triangle {
  // private data members
 private:
  int angle_1, angle_2;

  // public member functions
 public:
  // putAngles() function to insert angles
  // of the Triangle
  void putAngles() {
    cout << "Enter 1st Angle: ";
    cin >> angle_1;

    cout << "Enter 2nd Angle: ";
    cin >> angle_2;
  }

  // getAngle() function to find out the third angle
  int getAngle() {
    // initializing int type variable angle
    // to find third angle
    int angle;

    angle = 180 - (angle_1 + angle_2);

    // returning angle
    return angle;
  }
};

int main() {
  // create object
  Triangle T;

  // int type variable to store third angle
  int angle;

  // calling putAngles() function to insert angles
  T.putAngles();

  // calling getAngle() function to find 
  // third angle of triangle
  angle = T.getAngle();

  cout << "Third Angle:" << angle << endl;

  return 0;
}

Output:

Enter 1st Angle: 65
Enter 2nd Angle: 35
Third Angle: 80

Explanation:

In the above code, we have created a class Triangle, two int type data members angle_1 and angle_2 to store the angles of the triangle, and public member functions putAngles() and getAngle() to store angles and to find the third angle.

In the main() function, we are creating an object T of class Triangle, reading the inputted values by the user using putAngles() function, and finally calling the getAngle() member function to find third angle of the triangle. The getAngle() function contains the logic to find the third angle of the triangle and printing the result.

C++ Class and Object Programs (Set 2) »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.