LearnFrenzy
Sign in Take a free test

Decision Making · Decision Making Programs · Question 5

Check whether three sides form a right-angled triangle in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

The sides may be given in any order. Decide whether they form a right-angled triangle.

Solution
main.c
#include <stdbool.h>
#include <stdio.h>

bool is_right(long a, long b, long c) {
    if (a <= 0 || b <= 0 || c <= 0)
        return false;
    return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a;
}

int main(void) {
    long t[][3] = {{3, 4, 5}, {5, 12, 13}, {13, 5, 12}, {2, 3, 4}};
    for (int i = 0; i < 4; i++)
        printf("%ld %ld %ld: %s\n", t[i][0], t[i][1], t[i][2], is_right(t[i][0], t[i][1], t[i][2]) ? "right-angled" : "not right-angled");
    return 0;
}

Output Verified by compiling and running

3 4 5: right-angled
5 12 13: right-angled
13 5 12: right-angled
2 3 4: not right-angled

Testing all three ways the hypotenuse could be placed avoids sorting. Integer arithmetic keeps the Pythagoras check exact – with doubles, rounding could break the equality.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links