I am new to coding and trying some assignments. I am trying to prompt a user for the lengths of the sides of a triangle. The program calculates the area and returns a value. I am trying to use a while loop to reprompt the user if the given lengths do not create a triangle.
While (true)
{
SideA = parseFloat(prompt("Enter the length of Side A"));
SideB = parseFloat(prompt("Enter the length of Side B"));
SideC = parseFloat(prompt("Enter the length of Side C"));
//Calculate half the perimeter of the triangle
S = parseFloat(((SideA+SideB+SideC)/2));
//Calculate the area
Area = parseFloat(Math.sqrt((S*(S-SideA)*(S-SideB)*(S-SideC))));
if(isNaN(Area))
{
alert("The given values do not create a triangle. Please re-
enter the side lengths.");
}
else
{
break;
}
}
//Display results
document.write("The area of the triangle is " + Area.toFixed(2) + "."
+ PA);
You can use a do while loop to achieve this:
function checkTriangleInequality(a, b, c) {
return a < b + c && b < c + a && c < b + a;
}
function promptSides() {
let a, b, c;
while (true) {
a = parseFloat(prompt("Enter a"));
b = parseFloat(prompt("Enter b"));
c = parseFloat(prompt("Enter c"));
if (!checkTriangleInequality(a, b, c)) {
alert("Input is invalid, please try again.")
} else {
let s = (a+b+c)/2
let area = parseFloat(Math.sqrt((s*(s-a)*(s-b)*(s-c))));
console.log(area);
break;
}
}
}