|
|
|
| TABLE 4.1 THE RELATIONAL OPERATORS | | Name | Operator | Sample | Evaluates | | Equals | == | 100 == 50; | false | | | 50 == 50; | true | | Not Equals | != | 100 != 50; | true | | | 50 != 50; | false | | Greater Than | > | 100 > 50; | true | | | 50 > 50; | false | | Greater Than or Equals | >= | 100 >= 50; | true | | | 50 >= 50; | true | | Less Than | < | 100 < 50; | false | | | 50 < 50; | false | | Less Than or Equals | <= | 100 <= 50; | false | | | 50 <= 50; | true |
|
|
|
|
|
|
Normally, your program flows along line by line in the order in which it appears in your source code. The if statement enables you to test for a condition (such as whether two variables are equal) and branch to different parts of your code depending on the result. |
|
|
|
|
|
|
|
|
The simplest form of an if statement is this: |
|
|
|
|
|
|
|
|
if (expression)
statement; |
|
|
|
|
|
|
|
|
The expression in the parentheses can be any expression at all, but it usually contains one of the relational expressions. If the expression has the value zero, it is considered false, and the statement is skipped. If it has any nonzero value, it is considered true, and the statement is executed. Look at this example: |
|
|
|
|
|
|
|
|
if (bigNumber > smallNumber)
bigNumber = smallNumber; |
|
|
|
|
|
|
|
|
This code compares bigNumber and smallNumber. If bigNumber is larger, the second line sets its value to the value of smallNumber. |
|
|
|
|
|
|
|
|
Often your program will want to take one branch if your condition is true, another if it is false. |
|
|
|
|
|