# Find other two sides and angles of a right angle triangle in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In this problem, we are given an integer a denoting one side of a right angle triangle. We need to check whether it is possible to have a right angle triangle with side a. If it is possible, then find the other two sides and angle of a right angle triangle.

Let’s take an example to understand the problem,

## Input

a = 5

## Output

Sides : 5, 12, 13
Angles : 67.38, 22.62, 90

## Explanation

The sides of right angle are found as 52 + 122 = 132 And using these sides we can find the angles are, Sin-1 (5/13) and 90 - Sin-1 (5/13).

## Solution Approach

A simple solution to the problem is using pythagoras theorem. We know that the sides of a right angled triangle follow pythagoras theorem, which is

a2 + b2 = c2

Where a and b are sides of the triangle and c is the hypotenuse of the triangle.

Using this, we will calculate values of b and c using a.

Case 1 − If a is even,

c = (a2 + 4) + 1
b = (a2 + 4) - 1

Case 2 − If a is odd,

c = (a2 + 1)/ 2
c = (a2 - 1)/ 2

To find angles, we need to find sides of the triangle and using these values find the cos values.

cos(A) = b2 + c2 - a2 / 2bc
cos(B) = a2 + c2 - b2 / 2ac
cos(C) = a2 + b2 - c2 / 2ab

Program to illustrate the working of our solution,

## Example

Live Demo

#include <bits/stdc++.h>
#include <cmath>
using namespace std;
#define PI 3.1415926535
void printAngles(int a, int b, int c) {
double x = (double)a;
double y = (double)b;
double z = (double)c;
double A = (((double)(acos(( (y*y) + (z*z) - (x*x) ) / (2*y*z))))* 180 / PI);
double B = ((double)(acos(( (x*x) + (z*z) - (y*y) ) / (2*x*z)))* 180 / PI);
cout<<"Angles: A = "<<A<<", B = "<<B<<", C = 90";
}
void printOtherSides(int n) {
int b,c;
if (n & 1) {
if (n == 1)
cout << -1 << endl;
else{
b = (n*n-1)/2;
c = (n*n+1)/2;
}
} else {
if (n == 2)
cout << -1 << endl;
else {
b = n*n/4-1;
c = n*n/4+1;
}
}
cout<<"Sides : a = "<<n<<", b = "<<b<<", c = "<<c<<endl;
printAngles(n,b,c);
}
int main() {
int a = 5;
printOtherSides(a);
return 0;
}

## Output

Sides : a = 5, b = 12, c = 13
Angles: A = 22.6199, B = 67.3801, C = 90