A Note on Mutual Exclusion
You could write a square root program like this:
1 TextWindow.Write("Please enter the object's height (meters): ")
2 height = TextWindow.ReadNumber()
3 If (height < 0 ) Then
4 TextWindow.WriteLine("Don't be so negative!")
6 If ( height >= 0 ) Then
7 time = Math.SquareRoot(10 * height / 49)
8 time = Math.Round( time * 100 ) / 100 ' Rounds to 2 decimal places
9 TextWindow.WriteLine("Fall time = " + ans + " sec. ")
This program gives the same output as Listing 7-4, but it doesn’t use Else.
If the input number’s less than 0, the program prints the error message on Line 4 and then checks the next condition (height >= 0) on Line 6. If you think about this carefully, you’ll see that the second test in this case isn’t needed because the two conditions, (height < 0) and (height >= 0), are mutually exclusive (only one or the other is true). That means if height is less than 0, it can’t be greater than or equal to 0. The If/Else statement removes that second check! Using If/Else in this case is the way to go!
Learn more about Small Basic: Small Basic: Relational Operators & Strings
Have a Small and Basic day!
- Ninja Ed & Majed Marji