Â
In this, we are going to write a simple program to check if a triangle is valid or not using C++.
We first get values for the three sides of triangle from user.
check if sum of two sides is strictly greater than the third side, this condition is checked for all three combination of sum of two sides, then result is print that triangle is valid only if this condition all three sides is true.
We can write the logic in another way also...
if for any one of the three combinations if sum of two sides becomes less than or equal to third (which means not strictly greater than third side) then its an invalid triangle.
The code given below can be used for TURBO C++ Compiler:-
// validation of triangle using sides
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
double a,b,c;
cout<<"Enter sides of triangle\n";
cout<<"Enter value of Side a\n";
cin>>a;
cout<<"Enter value of Side b\n";
cin>>b;
cout<<"Enter value of Side c\n";
cin>>c;
// sum of two sides must be strictly greater than third side
// Eg 3,4,5 or 2,5,6--- valid triangle
// 1,2,3 or 1,11,10 --- not valid triangle
if((a+b) <= c || (a+c) <= b || (b+c) <= c)
{
cout<<"NOT a valid triangle";
}
else{
cout<<"VALID triangle";
}
getch();
}
The code given below can be used for g++/gcc Compiler:-
// validation of triangle using sides
#include <iostream>
using namespace std;
int main()
{
double a,b,c;
cout<<"Enter sides of triangle\n";
cout<<"Enter value of Side a\n";
cin>>a;
cout<<"Enter value of Side b\n";
cin>>b;
cout<<"Enter value of Side c\n";
cin>>c;
// sum of two sides must be strictly greater than third side
// Eg 3,4,5 or 2,5,6--- valid triangle
// 1,2,3 or 1,11,10 --- not valid triangle
if((a+b) <= c || (a+c) <= b || (b+c) <= c)
{
cout<<"NOT a valid triangle";
}
else{
cout<<"VALID triangle";
}
return 0;
}
#ENJOYCODING
Â
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP