Скачиваний:
64
Добавлен:
15.03.2015
Размер:
4.31 Mб
Скачать
ANALYSIS

Working with Operators

89

It is important to understand what is happening in Listing 4.3. In lines 8 and 9, two variables are again being initialized to 0. These values are printed in line 11.

As you can see from the output, the result is that Val1 and Val2 equal 0. Line 13, which continues to line 14, prints the values of these two variables again. The values printed, though, are ++Val1 and Val2++. As you can see, the pre-increment operator is being used on Val1 and the post-increment operator is being used on Val2. The results can be seen in the output. Val1 is incremented by 1 and then printed. Val2 is printed and then incremented by 1. Lines 16 and 19 repeat these same operations two more times.

DO

DONT

DO use the compound operators to make your math routines concise.

DON’T confuse the post-increment and pre-increment operators. Remember the pre-increment adds prior to the variable, and the post-increment adds after.

Relational Operators

Questions are a part of life. In addition to asking questions, it is often important to com-

4

pare things. In programming, you will compare values and then execute code based on the answer. The relational operators are used to compare two values.

With the relational operators, you determine the relationship between two values. The relational operators are listed in Table 4.2.

TABLE 4.2 Relational Operators

Operator

Description

>

Greater than

<

Less than

==

Equal to

!=

Not equal to

>=

Greater than or equal to

<=

Less than or equal to

 

 

When making comparisons with relational operators, you get one of two results: true or false. Consider the following comparisons made with the relational operators:

5 < 10 5 is less than 10, so this is true

5 > 10 5 is not greater than 10, so this is false

90

Day 4

5 == 10 5 does not equal 10, so this is false

5 != 10 5 does not equal 10, so this is true

As you can see, each of these results is either true or false. Knowing that you can check the relationship of values should be great for programming. The question is, how do you use these relations?

The if Statement

The value of relational operators is that they can be used to make decisions. These decisions are used to change the flow of the execution of your program. The if keyword can be used with the relational operators to change the program flow.

The if keyword is used to compare two values. The standard format of the if command is

if( val1 [operator] val2) statement(s);

Where operator is one of the relational operators; val1 and val2 are variables, constants, or literals; and statement(s) is a single statement or a block containing multiple statements. Remember a block is one or more statements between brackets.

If the comparison of val1 to val2 is true, the statements are executed. If the comparison of val1 to val2 is false, the statements are skipped. Figure 4.1 illustrates how the if command works.

FIGURE 4.1

The if command.

true

Condition Statement(s)

false

Applying this to an example helps make this clear. Listing 4.4 presents simple usage of the if command.

LISTING 4.4 iftest.cs—Using the if Command

1:// iftest.csThe if statement

2://----------------------------------------------------

ANALYSIS
OUTPUT

Working with Operators

91

LISTING 4.4 continued

4:class iftest

5:{

6:static void Main()

7:{

8:int Val1 = 1;

9:int Val2 = 0;

11: System.Console.WriteLine(“Getting ready to do the if...”); 12:

13:if (Val1 == Val2)

14:{

15:System.Console.WriteLine(“If condition was true”);

16:}

17:System.Console.WriteLine(“Done with the if statement”);

18:}

19:}

Getting ready to do the if...

Done with the if statement

This listing uses the if statement in line 13 to compare two values to see

whether they are equal. If they are, it prints line 15. If not, line 15 is skipped. 4 Because the values assigned to Val1 and Val2 in lines 8 and 9 are not equal, the if

condition fails and line 15 is not printed.

Change line 13 to

if (Val1 != Val2)

Rerun the listing. This time, because Val1 does not equal Val2, the if condition evaluates to true. The following is the output:

Getting ready to do the if...

If condition was true

Done with the if statement

 

 

 

 

 

 

Caution

 

There is not a semicolon at the end of the first line of the if command. For

 

 

 

example, the following is incorrect:

 

 

 

 

 

 

 

 

if( x != x);

 

 

 

 

 

 

 

 

{

 

 

 

 

// Statements to do when the if evaluates to true (which will

 

 

 

 

never happen)

 

 

 

 

}

 

 

 

 

 

 

 

 

 

 

 

92

Day 4

x should always equal x, so x != x will be false and the line // Statements to do when the if evaluates to true... should never execute. Because there is a semicolon at the end of the first line, the if statement is ended.

This means that the next statement after the if statement will be executed— the line //Statements to do when the if evaluates to true.... This line will always execute regardless of whether the if evaluates to true or, as in this case, to false. Make sure you don’t make the mistake of including a semicolon at the end of the first line of an if statement.

Conditional Logical Operators

The world is rarely a simple place. In many cases you will want to do more than one comparison to determine whether a block of code should be executed. For example, you might want to execute some code if a person is a female and at least 21 years old. To do this, you execute an if statement within another if statement. The following pseudocode illustrates this:

if( sex == female )

{

if( age >= 21)

{

// The person is a female that is 21 years old or older.

}

}

There is an easier way to accomplish this—by using a conditional logical operator.

The conditional logical operators enable you to do multiple comparisons with relational operators. The two conditional logical operators that you will use are the AND operator (&&) and the OR operator (||).

The Conditional AND Operator

There are times when you want to verify that a number of conditions are all met. The previous example was one such case. The logical AND operator (&&) enables you to verify that all conditions are met. You can rewrite the previous example as follows:

If( sex == female && age >= 21)

{

// This person is a female that is 21 years old or older.

}

You can actually place more than two relationships within a single if statement. Regardless of the number of comparisons, the comparisons on each side of the AND (&&) must be true. For example:

Working with Operators

93

if( x < 5 && y < 10 && z > 10)

{

// statements

}

The statements line is reached only if all three conditions are met. If any of the three conditions in the if statements are false, the statements are skipped.

The Conditional OR Operator

There are also times when you do not want all the conditions to be true: instead, you need only one of a number of conditions to be true. For example, you want might want to execute some code if the day of week is Saturday or Sunday. In these cases, you use the logical OR operator (||). The following illustrates this with pseudocode:

if( day equals sunday OR day equals saturday )

{

// do statements

}

 

In this example, the statements are executed if the day equals either sunday or saturday.

 

Only one of these conditions needs to be true for the statements to be executed. Listing

 

4.5 presents both the logical AND and OR in action.

4

 

LISTING 4.5 and.cs—Using the Logical AND and OR

1:// and.csUsing the conditional AND and OR

2://----------------------------------------------------

4:class andclass

5:{

6:static void Main()

7:{

8:int day = 1;

9:char sex = ‘f’;

11:System.Console.WriteLine(“Starting tests... (day:{0}, sex:{1})”,

12:

 

day, sex );

13:

 

 

14:

if ( day >= 1 && day <=7 )

//day from 1 to 7?

15:{

16:System.Console.WriteLine(“Day is from 1 to 7”);

17:}

18:if (sex == ‘m’ || sex == ‘f’ ) // Male or female?

19:{

20:System.Console.WriteLine(“Sex is male or female.”);

21:}

22:

23: System.Console.WriteLine(“Done with the checks.”);

94

Day 4

LISTING 4.5 continued

24:}

25:}

OUTPUT

Starting tests... (day:1, sex:f)

Day is from 1 to 7

 

Sex is male or female.

 

Done with the checks.

 

This listing illustrates both the && and || operators. In line 14 you can see the

ANALYSIS

 

AND operator (&&) in action. For this if statement to evaluate to true, the day

 

must be greater than or equal to 1 as well as less than or equal to 7. If the day is 1, 2, 3, 4, 5, 6, or 7, the if condition evaluates to true and line 16 prints. Any other number results in the if statement evaluating to false, and line 16 will be skipped.

Line 18 shows the OR (||) operator in action. Here, if the value in sex is equal to the character ‘m’ or the character ‘f’, line 20 is printed; otherwise, line 20 is skipped.

 

 

 

Caution

 

Be careful with the if condition in line 18. This checks for the characters ‘m’

 

and ‘f’. Notice these are lowercase values, which are not the same as the

 

 

 

 

uppercase values. If you set sex equal to ‘F’ or ‘M’ in line 9, the if

 

 

 

 

statement in line 18 would still fail.

 

 

 

Change the values in lines 8 and 9 and rerun the listing. You’ll see that you get different output results based on the values you select. For example, change lines 8 and 9 to the following:

8:int day = 9;

9:char sex = ‘x’;

Here are the results of rerunning the program:

Starting tests... (day:9, sex:x)

OUTPUT Done with the checks.

There are also times when you will want to use the AND (&&) and the OR (||) commands together. For example, you might want to execute code if a person is 21 and is either a male or female. This can be accomplished by using the AND and OR statements together. You must be careful when doing this, though. An AND operator expects the values on both sides of it to be true. An OR statement expects one or the other value to be true. For the previous example, you might be tempted to enter the following:

if( age >= 21 AND gender == male OR gender == FEMALE) // statement