Solve for any Side

More with Pythagoras

We've solved for the hypotenuse, but what if we want to solve for one of the sides of a right triangle? We can till use the Pythagorean Theorem we just have to do a little algebra first. so if we wanted to solve for a side we'd use code like:

This will allow use to calculate side b. With a simple modification you could also easily make it calculate side a instead. It is also possible to write a sketch that will take any two sides and give us the third.

This relies on us using some new code:

  if (a==0)

This is an "if" function. It asks the questions, is this true? In this case it is asking if a equals zero. We must use double equal sign to ask do these two equal each other. One of the most common mistakes is to use a single equal sign here. The single equal sign will not ask the questions is a equal to zero. It will instead change the value of a to be zero.

If the statement in parenthesis is true then the code in the curly braces is run. If the statement is false then the code in the curly braces is skipped.

You may also have noticed that the "if" line does not end in a semi-colon. This is true of any line that is immediately followed by a set of curly braces. You'll notice neither setup nor loop are followed by semi-colons either.

Comparison Operators

The double equals sign is a comparison operator. In the table below are the other comparison operators you can use with an if statement.

 x==y  x is equal to y
 x!=y  x is not equal to y
 x>y  x is greater than y
 x>=y  x is greater than or equal to y
 x<y  x is less than y
 x<=y  x is less than or equal to y

More Stuff

You might need what follows to do the Chapter 4 Assignment. It will at least help you think about different ways of completing the assignment. You might want to ask two questions in the same if statement. In this case you would use a Boolean Operator. So if you wanted to ask two questions and wanted both to be true you'd ask:
  if (a>0 && a<10)
This would be true only if a had a value between 0 and 10. You could tack on more &&'s and ask three or more questions as well. If you needed only one of the statements to be true you would use or instead of and. For or in Arduino, and many other programing languages, you use the "pipe" (shift-backslash). Just as and requires double-ampersands &&, or requires double-pipe ||:
  if (a>=0 || b>=0)
Would be true if either or both statements were true.

You might also want to investigate else and else if. This can be another way to ask multiple questions at the same time. For more detail on this you should check out the Arduino Reference entry on Else.