
The Pythagorean theorem (programming)

Upgrade for more content
What is pseudocode?
You know about Pythagoras' Theorem? Then you know how to calculate the lengths of the sides of a right-angle triangle. But, it takes a lot of calculation... And maybe you need to repeat these steps over and over again. Imagine a program where you could input the two short sides - the legs - and instantly get the long side of the triangle - the hypotenuse!
Now we are going to write just such a program! When we program, the first thing we do is split the problem up into small steps. Each step needs to be so specific, you could give it as an instruction to a robot that knows nothing about anything; and the robot could follow it correctly. So how would you explain to a robot how to calculate the length of the hypotenuse using the lengths of the two legs? In order to start calculating, the robot needs some data.
So we write: "Note leg1 Note leg2" Now the robot has the information needed. What should it do then? Try writing some more instructions yourself! Perhaps you have written something like this? Okay, it looks good.
But maybe the robot needs clearer instruction for these calculations? Let's clarify a little bit. Imagine asking the robot to use a calculator for you. How would you phrase the instructions then? There.
Now the instructions can't be misunderstood, right? What we have written here is almost code, but not proper programming code. We call it the pseudocode of our program. Pseudocode - Is this the same as the algorithm for solving Pythagoras' theorem? Well, not really.
This is the part of the code that solves the task itself. This is the algorithm. You might be more used to seeing it like this? What does the rest of the code do? It is also a form of algorithm, but it has nothing to do with the calculation itself.
What it does is take in the values of the lengths of the triangle legs, and then output the result. These rows in the middle solve the task itself. We can use these rows in many different situations to calculate the hypotenuse of any right-angle triangle. There. Now you have all that's needed.
Time to bring out your programming tool, write this program, and see that it works! Does it look too difficult? We can make it a bit clearer by drawing a flowchart. We draw one box for each step. Create a variable, call it a, and give it the value of the first leg.
Do the same for the other leg. This variable gets the name 'b'. Calculate the square of a, and give that value to a new variable, called a2. Do the same for b, and put that value in a variable that we name: b2. Create the variable c2, and give it the value of a2 plus b2.
Finally, create the variable c and give it the value: the square root of c2! Show the result. The result that the program puts out is the value of the variable c, which equals the length of the hypotenuse! Now, it's time for you to start programming!