Tuesday, January 14, 2014

This  section introduces C#’s if  structure,  which allows a program  to make a decision
based on the truth or falsity of some condition. If the condition is met (i.e., the condition is
true), the statement in the body of the if structure executes. If the condition is not met (i.e.,
the condition is false), the body statement does not execute. Conditions in if structures can
be  formed  by  using  the  equality  operators  and  relational  operators,  summarized  in
Fig. 3.18. The relational operators all have the same level of precedence and associate from
left to right. The equality operators both have the same level of precedence, which is lower
than the precedence of the relational operators. The equality operators also associate from
left to right.

          Common Programming Error 3.7
It is a syntax error if the operators ==, !=, >= and<=  contain spaces between their symbols
(as in = =, ! =, > =, < =).                                                                                             
     
         Common Programming Error 3.8
Reversing the operators !=, >= and <= (as in =!, => and =<) is a syntax error.     




         Common Programming Error 3.9
Confusing the equality operator == with the assignment operator = is a logic error. The
equality operator should be read “is equal to,” and the assignment operator should be read
“gets” or “gets the value of.” Some people prefer to read the equality operator as “double
equals” or “equals equals.”    

     The next example uses six if statements to compare two numbers input into a program
by the user. If the condition in any of these if statements is true, the assignment statement
associated with that if executes. The user inputs values that the program converts to inte-
gers and stores in variables number1 and number2. The program compares the numbers
and  displays  the  results  of  the  comparison  in  the  command  prompt.  The  program  and
sample outputs are shown in Fig. 3.19.

                                         
     The definition of class Comparison begins on line 7, and the Main method begins
on line 9. Lines 11–12 declare the variables used in method Main. Note that there are two
variables of type int. Remember that variables of the same type may be declared in one
declaration or in multiple declarations. Also recall that, if more than one variable is placed
in one declaration (lines 11–12), those variables are separated by commas (,). The com-
ment at the end of each line indicates the purpose of each variable in the program.

      Line 16 reads in the first number from the user. Line 20 reads in the second number from
the user. These values are stored in variables number1 and number2, respectively. Recall
that arithmetic operators cannot be used with strings. Relational and equality operators also
cannot be used with strings. Therefore, the two input strings must be converted to integers.

     Lines 16 and 20 both get an input, convert the input to type int and assign the values
to the appropriate variable in one step. Notice that this step can be combined with the vari-

able declaration and placed on one line with the statement

               int number1 = Int32.Parse( Console.ReadLine() );

which declares the variable, reads a string from the user, converts the string to an integer

and stores the integer in the variable.
     The if structure in lines 22–23 compares the values of the variables number1 and
number2  for  equality.  If  the  values  are  equal,  the  program  outputs  the  value  of
number1+"=="+number2. Notice that this expression uses the operator + to “add”
(or combine) numbers and strings. C# has a version of the + operator used for string con-
catenation. Concatenation is the process that enables a string and a value of another data
type (including another string) to be combined to form a new string.
     If  number1  contains  the  value  1000  and  number2  contains  the  value  1000,  the
expression evaluates as follows: C# determines that the operands of the + operator are of dif-
ferent types and that one of them is a string. Next, number1 and number2 are converted
to a string and concatenated with " == ". At this point, the string, namely "1000 ==
1000", is sent to Console.WriteLine to be output. As the program proceeds through
the if structures, more strings will be output by these Console.WriteLine state-
ments. For example, given the value 1000 for number1 and number2, the if conditions
at lines 34 (<=) and 37 (>=) will also be true. Thus, the output displayed will be

               1000 == 1000
               1000 <= 1000
               1000 >= 1000

The second of output window of Fig. 3.19 demonstrates this case.


          Common Programming Error 3.10
Confusing the + operator used for string concatenation with the + operator used for addition
can lead to strange results. For example, assuming integer variable y has the value 5, the
expression "y + 2 = " + y + 2 results in the string "y + 2 = 52", not "y + 2 = 7". First
the value of y  (5) is concatenated with the string "y + 2 = ", then the value 2 is concate-
nated with the new, larger string "y + 2 = 5". The expression "y + 2 = " + (y + 2) pro-
duces the desired result.  
                                                                                               
          Common Programming Error 3.11
Replacing operator == in the condition of an if structure, such as if ( x == 1 ), with  
operator =, as in if ( x = 1 ), is a logic error.    

Notice the indentation in the if statements throughout the program. Such indentation

enhances program readability.

          Good Programming Practice 3.14
Indent the statement in the body of an if structure to make the body of the structure stand
out and to enhance program readability.           
                                                                    
          Good Programming Practice 3.15
Place only one statement per line in a program. This enhances program readability.

          Common Programming Error 3.12
Forgetting the left and right parentheses for the condition in an if structure is a syntax er-
ror. The parentheses are required.       

     There is no semicolon (;) at the end of the first line of each if structure. Such a semi-
colon would result in a logic error at execution time. For example,

          if ( number1 == number2 );
                Console.WriteLine( number1 + " == " + number2 );   

would actually be interpreted by C# as

          if ( number1 == number2 )
          ;
         Console.WriteLine( number1 + " == " + number2 );       

where the semicolon on the line by itself—called the empty statement—is the statement to
execute if the condition is true. When the empty statement executes, no task is performed.
The program continues with the Console.WriteLine statement, which executes re-
gardless of whether the condition is true or false.

          Common Programming Error 3.13
Placing a semicolon immediately after the right parenthesis of the condition in an if struc-
ture is normally a logic error. The semicolon causes the body of the if structure to be empty,
so the if structure performs no action, regardless of whether its condition is true. Worse,
the intended body statement of the if structure becomes a statement in sequence with the if
structure and always executes.                            

     Notice the use of spacing in Fig. 3.19. Remember that the compiler normally ignores
whitespace characters, such as tabs, newlines and spaces. Statements may be split over sev-
eral lines and may be spaced according to the programmer’s preferences without affecting
the meaning of a program. It is incorrect to split identifiers and string literals. Ideally, state-
ments should be kept small, but it is not always possible to do so.

          Good Programming Practice 3.16
A lengthy statement may be spread over several lines. If a single statement must be split
across lines, choose breaking points that make sense, such as after a comma in a comma-
separated list or after an operator in a lengthy expression. If a statement is split across two
or more lines, indent all subsequent lines with one level of indentation. 

     The chart in Fig. 3.20 shows the precedence of the operators introduced in this chapter.
The operators are displayed from top to bottom in decreasing order of precedence. Notice
that all these operators, with the exception of the assignment operator =, associate from left
to right. Addition is left associative, so an expression such as x + y + z is evaluated as if it
were written (x + y) + z. The assignment operator = associates from right to left, so an
expression such as x = y = 0 is evaluated as if it were written x = (y = 0). The latter
expression, x = (y = 0), first assigns the value 0 to variable y and then assigns the result
of that assignment, 0, to x.

          Common Programming Error 3.13
Placing a semicolon immediately after the right parenthesis of the condition in an if struc-
ture is normally a logic error. The semicolon causes the body of the if structure to be empty,
so the if structure performs no action, regardless of whether its condition is true. Worse,
the intended body statement of the if structure becomes a statement in sequence with the if
structure and always executes.     

     Notice the use of spacing in Fig. 3.19. Remember that the compiler normally ignores
whitespace characters, such as tabs, newlines and spaces. Statements may be split over sev-
eral lines and may be spaced according to the programmer’s preferences without affecting
the meaning of a program. It is incorrect to split identifiers and string literals. Ideally, state-

ments should be kept small, but it is not always possible to do so.

        Good Programming Practice 3.16
A lengthy statement may be spread over several lines. If a single statement must be split
across lines, choose breaking points that make sense, such as after a comma in a comma-
separated list or after an operator in a lengthy expression. If a statement is split across two
or more lines, indent all subsequent lines with one level of indentation.    

    In this chapter, we introduced important features of C#, including displaying data on
the screen, inputting data from the keyboard, performing calculations and making deci-
sions. The next chapter demonstrates many similar techniques, as we reintroduce C# Win-
dows applications (applications that provide a graphical user interface). We also introduce
structured programming and familiarize the reader further with indentation techniques. We
study how to specify and vary the order in which statements execute—this order is called
flow of control.            


0 comments:

Post a Comment

Subscribe to RSS Feed Follow me on Twitter!