**Algorithms** – Java Program to find if Triangle can be formed using given 3 sides

**Objective**– Given 3 side lengths, write a program to find out if using these 3 sides, a triangle can be formed.

**Example**:

Triangle can be formed using side 2.5, 3.5, 5.0 Triangle cannot be formed using side 1.0, 3.0, 5.0 Sum of 1.0 and 3.0 is not > 5.0

**Approach**:

- If sum of length of any two sides is strictly greater than the length of third side then triangle can be constructed, else we cannot construct a triangle.
- Say sides lengths given are- a, b, c then to form a triangle, a+b>c and b+c>a, a+c>b. If any of the condition is not true, triangle cannot be formed.

**Java Code**:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.

Learn more about bidirectional Unicode characters

public class CheckTriangle { | |

public static void checkTriangleFormed(double a, double b, double c){ | |

//check all combinations, | |

//sum of any 2 sides must be greater than the third side to form a triangle | |

if(check(a, b, c) && check(a, c, b) && check(b, c, a)) | |

System.out.println("Triangle can be formed using side " + a + ", " + b + ", " +c ); | |

else | |

System.out.println("Triangle cannot be formed using side " + a + ", " + b + ", " +c ); | |

} | |

public static boolean check(double x, double y, double z){ | |

//check if sum of x and y is greater than z | |

if((x+y)>z) | |

return true; | |

System.out.println("Sum of " + x + " and "+ y + " is not > " + z); | |

return false; | |

} | |

public static void main(String[] args) { | |

double a = 2.5; | |

double b = 3.5; | |

double c = 5; | |

checkTriangleFormed(a, b, c); | |

System.out.println("________________________"); | |

a = 1; | |

b = 3; | |

c = 5; | |

checkTriangleFormed(a, b, c); | |

} | |

} |

**Output**:

Triangle can be formed using side 2.5, 3.5, 5.0 _____________________ Sum of 1.0 and 3.0 is not > 5.0 Triangle cannot be formed using side 1.0, 3.0, 5.0