# Manipulating Values in Your Programs

• Print
This chapter is from the book

## Making Comparisons with Relational Operators

Questions are a part of life. In addition to asking questions, it is often important to compare things. In programming, you compare values and then execute code based on the answer. The relational operators are used to compare two values. The relational operators are listed in Table 3.2.

#### Table 3.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. 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?

### Using the if Statement

The value of relational operators is that they can be used to make decisions 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 as follows:

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

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 that 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 3.1 illustrates how the if command works.

Figure 3.1 The if command.

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

#### Listing 3.4 iftest.cs—Using the if Command

``` 1: // iftest.cs- The if statement
2: //----------------------------------------------------
3:
4: class iftest
5: {
6:   public static void Main()
7:   {
8:    int Val1 = 1;
9:    int Val2 = 0;
10:
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, it skips Line 15. Because the values assigned to Val1 and Val2 in Lines 8–9 are not equal, the if condition fails and Line 15 is not printed.

Change Line 13 to this:

`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 no semicolon at the end of the first line of the if command. For example, the following is incorrect:

```if( val != val );
{
// Statements to do when the if evaluates to true (which will    // never happen)
}```

val should always equal val, so val != val 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 is executed—the line //Statements to do when the if evaluates to true.... This line always executes, regardless of whether the if evaluates to true or, as in this case, to false. 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

Sometimes 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:

```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 is false, the statements are skipped.

#### The Conditional OR Operator

Also sometimes, 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 3.5 presents both the logical AND and OR in action.

#### Listing 3.5 and.cs—Using the Logical AND and OR

``` 1: // and.cs- Using the conditional AND and OR
2: //----------------------------------------------------
3:
4: class andclass
5: {
6:   public static void Main()
7:   {
8:    int day = 1;
9:    char sex = 'f';
10:
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.");
24:   }
25: }
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 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 thus 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–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–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)
Done with the checks.```

Other times you will want to use the AND (&&) and OR (||) commands together. For example, you might want to execute code if a person is 21 and is either a male or a 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 of the values to be true. For the previous example, you might be tempted to enter the following (note that this is pseudocode):

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

This will not accomplish what you want. If the person is 21 or older and is a female, the statement will not execute. The AND portion will result in being false. To overcome this problem, you can force how the statements are evaluated using the parenthesis punctuator. To accomplish the desired results, you would change the previous example to this:

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

The execution always starts with the innermost parenthesis. In this case, the statement (gender == male OR gender == female) is evaluated first. Because this uses OR, this portion of the statement will evaluate to true if either side is true. If this is true, the AND will compare the age value to see whether the age is greater than or equal to 21. If this proves to be true as well, the statement will execute.

TIP

Use parentheses to make sure that you get code to execute in the order you want.

Do use parentheses to make complex math and relational operations easier to understand.

Don't confuse the assignment operator (=) with the relational equals operator (==).