Decision Making: Equality and Relational Operators

Một phần của tài liệu Visual C 2012 How to Program _ www.bit.ly/taiho123 (Trang 131 - 135)

2. When the app executes, another compiler (known as the just-in-time compiler

3.9 Decision Making: Equality and Relational Operators

Aconditionis an expression that can be eithertrueorfalse. This section introduces a sim- ple version of C#’sifstatementthat allows an app to make adecisionbased on the value of a condition. For example, the condition “grade is greater than or equal to 60” deter- mines whether a student passed a test. If the condition in anifstatement is true, the body of theifstatement executes. If the condition is false, the body doesnotexecute. We’ll see an example shortly.

Conditions inifstatements can be formed by using theequality operators(==and

!=) andrelational operators(>,<,>=and<=) summarized in Fig. 3.21. The two equality operators (== and !=) each have the same level of precedence, the relational operators (>,

<, >= and <=) each have the same level of precedence, and the equality operators have lower precedence than the relational operators. They all associate from left to right.

Using theifStatement

Figure 3.22 uses sixifstatements to compare two integers entered by the user. If the con- dition in any of theseifstatements is true, the assignment statement associated with that

ifstatement executes. The app uses classConsoleto prompt for and read two lines of text

y = ( a * x * x ) + ( b * x ) + c;

Common Programming Error 3.5

Confusing the equality operator,==, with the assignment operator,=, can cause a logic er- ror or a syntax error. The equality operator should be read as “is equal to,” and the assign- ment operator should be read as “gets” or “gets the value of.” To avoid confusion, some programmers read the equality operator as “double equals” or “equals equals.”

Standard algebraic equality and relational operators

C# equality or relational operator

Sample C#

condition

Meaning of C# condition Relational operators

> > x > y xis greater thany

< < x < y xis less thany

≥ >= x >= y xis greater than or equal toy

≤ <= x <= y xis less than or equal toy

Equality operators

= == x == y xis equal toy

≠ != x != y xis not equal toy

Fig. 3.21 | Relational and equality operators.

3.9 Decision Making: Equality and Relational Operators 91

from the user, extracts the integers from that text with theToInt32method of classCon-

vert, and stores them in variablesnumber1andnumber2. Then the app compares the num- bers and displays the results of the comparisons that are true.

1 // Fig. 3.22: Comparison.cs

2 // Comparing integers using if statements, equality operators 3 // and relational operators.

4 using System;

5

6 public class Comparison 7 {

8 // Main method begins execution of C# app 9 public static void Main( string[] args )

10 {

11 int number1; // declare first number to compare 12 int number2; // declare second number to compare 13

14 // prompt user and read first number 15 Console.Write( "Enter first integer: " );

16 number1 = Convert.ToInt32( Console.ReadLine() );

17

18 // prompt user and read second number 19 Console.Write( "Enter second integer: " );

20 number2 = Convert.ToInt32( Console.ReadLine() );

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

39 } // end Main

40 } // end class Comparison

Enter first integer: 42 Enter second integer: 42 42 == 42

42 <= 42 42 >= 42

Fig. 3.22 | Comparing integers usingifstatements, equality operators and relational operators.

(Part 1 of 2.)

if ( number1 == number2 )

Console.WriteLine( "{0} == {1}", number1, number2 );

if ( number1 != number2 )

Console.WriteLine( "{0} != {1}", number1, number2 );

if ( number1 < number2 )

Console.WriteLine( "{0} < {1}", number1, number2 );

if ( number1 > number2 )

Console.WriteLine( "{0} > {1}", number1, number2 );

if ( number1 <= number2 )

Console.WriteLine( "{0} <= {1}", number1, number2 );

if ( number1 >= number2 )

Console.WriteLine( "{0} >= {1}", number1, number2 );

ClassComparison

The declaration of classComparisonbegins at line 6

The class’sMainmethod (lines 9–39) begins the execution of the app.

Variable Declarations Lines 11–12

declare theintvariables used to store the values entered by the user.

Reading the Inputs from the User Lines 14–16

prompt the user to enter the first integer and input the value. The input value is stored in variablenumber1. Lines 18–20

perform the same task, except that the input value is stored in variablenumber2. Comparing Numbers

Lines 22–23

compare the values of the variablesnumber1andnumber2to determine whether they’re equal. Anifstatement always begins with keywordif, followed by a condition in paren-

Enter first integer: 1000 Enter second integer: 2000 1000 != 2000

1000 < 2000 1000 <= 2000

Enter first integer: 2000 Enter second integer: 1000 2000 != 1000

2000 > 1000 2000 >= 1000

public class Comparison

int number1; // declare first number to compare int number2; // declare second number to compare

// prompt user and read first number Console.Write( "Enter first integer: " );

number1 = Convert.ToInt32( Console.ReadLine() );

// prompt user and read second number Console.Write( "Enter second integer: " );

number2 = Convert.ToInt32( Console.ReadLine() );

if ( number1 == number2 )

Console.WriteLine( "{0} == {1}", number1, number2 );

Fig. 3.22 | Comparing integers usingifstatements, equality operators and relational operators.

(Part 2 of 2.)

3.9 Decision Making: Equality and Relational Operators 93

theses. Anifstatement expectsonestatement in its body. The indentation of the body statement shown here is not required, but it improves the code’s readability by emphasiz- ing that the statement in line 23 is part of theifstatement that begins in line 22. Line 23 executes only if the numbers stored in variablesnumber1andnumber2are equal (i.e., the condition is true). Theif statements in lines 25–26, 28–29, 31–32, 34–35 and 37–38 comparenumber1andnumber2with the operators!=,<,>,<=and>=, respectively. If the condition in any of theifstatements is true, the corresponding body statement executes.

No Semicolon at the End of the First Line of anifStatement

There’s no semicolon (;) at the end of the first line of eachifstatement. Such a semicolon would result in a logic error at execution time. For example,

would actually be interpreted by C# as

where the semicolon in the line by itself—called theempty statement—is the statement to execute if the condition in theifstatement is true. When the empty statement executes, no task is performed in the app. The app then continues with the output statement, which always executes, regardless of whether the condition is true or false, because the output statement is not part of theifstatement.

Whitespace

Note the use of whitespace in Fig. 3.22. Recall that whitespace characters, such as tabs, newlines and spaces, are normally ignored by the compiler. So statements may be split over

Common Programming Error 3.6

Omitting the left and/or right parentheses for the condition in anifstatement is a syntax error—the parentheses are required.

Common Programming Error 3.7

Reversing the operators!=,>=and<=, as in=!,=>and=<, can result in syntax or logic errors.

Common Programming Error 3.8

It’s a syntax error if the operators==,!=,>=and<=contain spaces between their symbols, as in= =,! =,> =and< =, respectively.

Good Programming Practice 3.11

Indent anifstatement’s body to make it stand out and to enhance app readability.

if ( number1 == number2 ); // logic error

Console.WriteLine( "{0} == {1}", number1, number2 );

if ( number1 == number2 )

; // empty statement

Console.WriteLine( "{0} == {1}", number1, number2 );

Common Programming Error 3.9

Placing a semicolon immediately after the right parenthesis of the condition in anifstate- ment is normally a logic error.

several lines and may be spaced according to your preferences without affecting the mean- ing of an app. It’s incorrect to split identifiers, strings, and multicharacter operators (like

>=). Ideally, statements should be kept small, but this is not always possible.

Precedence and Associativity of the Operators We’ve Discussed So Far

Figure 3.23 shows the precedence of the operators introduced in this chapter. The operators are shown from top to bottom in decreasing order of precedence. All these operators, with the exception of the assignment operator,=, associate from left to right. Addition is left as- sociative, so an expression likex + y + zis evaluated as if it had been written as(x + y) + z. The assignment operator,=, associates from right to left, so an expression likex = y = 0is evaluated as if it had been written asx = (y = 0), which, as you’ll soon see, first assigns the value0to variableythen assigns the result of that assignment,0, tox.

Một phần của tài liệu Visual C 2012 How to Program _ www.bit.ly/taiho123 (Trang 131 - 135)

Tải bản đầy đủ (PDF)

(1.020 trang)