Interactive tool with VB6 and VB.NET code examples
The Pythagorean Theorem is a fundamental principle in geometry that relates the three sides of a right-angled triangle. It states that the square of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the other two sides.
By referring to a right angled triangle ABC, where AC is the hypotenuse, the sides are connected by the formula:
AB2 + BC2 = AC2
Using this formula, you can calculate the third side if the length of any two sides are known. For example, if AB = 3 and BC = 4, then AC = 5.
Enter any two sides to calculate the third side of a right-angled triangle:
This VB6 code calculates the third side of a right-angled triangle when any two sides are provided:
Private Sub Command1_Click()
Dim AB, BC, AC As Single
' Get values from text boxes
AB = Val(Txt_AB.Text)
BC = Val(Txt_BC.Text)
AC = Val(Txt_AC.Text)
' Calculate the missing side
If AB <> 0 And BC <> 0 Then
AC = Sqr(AB ^ 2 + BC ^ 2)
Txt_AC.Text = Round(AC, 2)
ElseIf AB <> 0 And AC <> 0 Then
BC = Sqr(AC ^ 2 - AB ^ 2)
Txt_BC.Text = Round(BC, 2)
ElseIf BC <> 0 And AC <> 0 Then
AB = Sqr(AC ^ 2 - BC ^ 2)
Txt_AB.Text = Round(AB, 2)
Else
MsgBox "Please enter any two sides", vbExclamation
End If
End Sub
This VB.NET code provides the same functionality with modern .NET features:
Private Sub CalculateButton_Click(sender As Object, e As EventArgs) Handles CalculateButton.Click
Dim AB, BC, AC As Double
' Try to parse the input values
Dim abValid = Double.TryParse(txtAB.Text, AB)
Dim bcValid = Double.TryParse(txtBC.Text, BC)
Dim acValid = Double.TryParse(txtAC.Text, AC)
' Count how many sides were entered
Dim enteredSides = If(abValid, 1, 0) + If(bcValid, 1, 0) + If(acValid, 1, 0)
If enteredSides < 2 Then
MessageBox.Show("Please enter at least two sides", "Input Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
' Calculate the missing side
If abValid AndAlso bcValid Then
AC = Math.Sqrt(AB * AB + BC * BC)
txtAC.Text = Math.Round(AC, 2).ToString()
ElseIf abValid AndAlso acValid Then
BC = Math.Sqrt(AC * AC - AB * AB)
txtBC.Text = Math.Round(BC, 2).ToString()
ElseIf bcValid AndAlso acValid Then
AB = Math.Sqrt(AC * AC - BC * BC)
txtAB.Text = Math.Round(AB, 2).ToString()
End If
End Sub
Try extending the Pythagoras Theorem calculator with these features:
Advanced Challenge: Create a graphical representation of the triangle that scales based on the entered values.