w3resource

C++ Exercises: Check whether given length of three side form a right triangle


Check Right Triangle

Write a C++ program to check whether a given length of three sides forms a right triangle.

Visual Presentation:

C++ Exercises: Check whether given length of three side form a right triangle

Sample Solution:

C++ Code :

#include <iostream> // Including input-output stream header file
#include <vector>   // Including vector header file for vector container
#include <algorithm> // Including algorithm header file for sorting operations
using namespace std; // Using the standard namespace

int main() { // Start of the main function

    vector<int> triangle_sides(3); // Creating a vector 'triangle_sides' to store 3 integers (sides of a triangle)

    // Inputting 3 integers representing sides of a triangle into the vector
    cin >> triangle_sides[0] >> triangle_sides[1] >> triangle_sides[2];

    // Sorting the sides of the triangle in ascending order
    sort(triangle_sides.begin(), triangle_sides.end());

    // Checking if the given sides form a right-angled triangle using Pythagoras theorem
    if (triangle_sides[0] * triangle_sides[0] + triangle_sides[1] * triangle_sides[1] == triangle_sides[2] * triangle_sides[2]) {
        cout << "Yes" << endl; // If the sides form a right-angled triangle, output "Yes"
    } else {
        cout << "No" << endl; // If not, output "No"
    }

    return 0; // Indicating successful completion of the program
}

Sample Output:

Sample input : 6 9 7
Sample Output:
No

Flowchart:

Flowchart: Check whether given length of three side form a right triangle

For more Practice: Solve these Related Problems:

  • Write a C++ program to determine if three side lengths form a right triangle using the Pythagorean theorem with tolerance for floating-point errors.
  • Write a C++ program that reads three side lengths, checks for a right triangle, and then outputs a message indicating the type of triangle.
  • Write a C++ program to verify if a given triangle is right-angled by first sorting the sides and then applying the Pythagorean theorem.
  • Write a C++ program that accepts three side lengths, checks for a right triangle, and then calculates the area if it is right-angled.

Go to:


PREV : Sum of Two Integers and Digit Count.
NEXT : Sum from 1 to n.

C++ Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.