Counting Truth Values
Reference > Science > Technology > Beginner Programming TipsSuppose you have four variables, X, Y, Z and W, and you want to know how many of them are equal to 10. You could do it like this:
Dim Y As Integer
Dim Z As Integer
Dim Z As Integer
Dim C As Integer
'Find out how many are equal to 10
If X = 10 Then
C = C + 1
End If
If Y = 10 Then
C = C + 1
End If
If Z = 10 Then
C = C + 1
End If
If W = 10 Then
C = C + 1
End If
In this code, the variable C keeps track of the number of variables that are equal to 10. It works, but it takes twelve lines of code, and the same thing can be done with a single line of code. Really.
Remember that an equation has a value. It is eitherTrue, or it is False. What I haven't mentioned yet, but am telling you now, is that Although we think of Equations as being True or False, the computer has a very numerical way of describing that. If an equation is False, the computer says it has a value of Zero. But if it's True, the computer says it has a value of Negative One.
Does that seem strange to you? There are reasons why the computer uses zero and negative one for False and True, but we don't need to get into that right now. But keeping in mind how a computer thinks of True and False, take a look at the following line of code:
Dim Y As Integer
Dim Z As Integer
Dim Z As Integer
Dim C As Integer
'Find out how many are equal to 10
C = -(X = 10) -(Y = 10) -(Z = 10) -(W = 10)
Suppose that X = 10 and Z = 10. Then the Equation evaluates to:
C = - True - False - True - False C = - (-1) - 0 - (-1) - 0 C = 2
Pretty slick, eh?