JavaScript Tutorial JavaScript Examples JQuery Tutorial CSS Tutorial HTML Tutorial About Us

Pythagoras Theorem

The Pythagoras Theorem is used to solve problems related to the length of the sides of a triangle. The formula is


AB  is the opposite side, AC is the adjacent and BC is the hypotenuse of a triangle ABC.

We shall create a JavaScript application to deal with problems related to Pythagoras Theorem. In this application, we shall randomly generate the length of the opposite side and the length of the adjacent side of a triangle. The user can then click on the Calculate Hypotenuse button to find the answer.

The JavaScript is as follows:

function Calhypo(a,b){
var hypo=Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
return hypo;
function Cal_hypo(){
var  x=parseInt(document.getElementById("adjacent").innerHTML);
var  y=parseInt(document.getElementById("opposite").innerHTML);
var z=Calhypo(x,y);
var c=z.toFixed(2);
document.getElementById('ans').textContent="The Length of hypotenuse is= "+c;


Save the above script as pythagoras.js

We use the Math function


to find the square of a and b. The sqrt function is to find the square root of a number. We use the toFixed function to convert the resulting answer into 2 decimal places.

The HTML is as follows:

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Pythagoras Theorem</title>
<body onload="RandomFn()">
<h1>Pythagoras Theorem</h1>
<p>Length of adjacent side a=<b id="adjacent"></b></p>
<p>Length of opposite side b=<b id="opposite"></b></p>

<P id="ans">The Length of hypotenuse c is</p>
<input type="button" value="Calculate hypotenuse" onclick="Cal_hypo()"><br><br>
<input type="button" value="Next Question" onclick=" lRandomFn();">
function RandomFn() {
 document.getElementById("adjacent").innerHTML = parseInt(Math.random()*9+1);
 document.getElementById("opposite").innerHTML = parseInt(Math.random()*9+1);
<script type="text/javascript" src="pythagoras.js"></script>


* The function RandomFn() is to generate two random integers on loading the web page and when clicking the 'Next' button

Pythagoras Theorem in Action

Length of adjacent side a=

Length of opposite side b=

The Length of hypotenuse c is


Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy