3 decision making: equality and relational operators a condition is an expression that can be either...
TRANSCRIPT
3 Decision Making: Equality and Relational Operators
• A condition is an expression that can be either true or false.
• Conditions can be formed using the equality operators (== and !=) and relational operators (>, <, >= and <=) summarized in Fig. 3.25.
1
Fig. 3.25 | Equality and relational operators. (Part 1 of 2.)
Standard algebraic equality and relational operators
C# equality or relational operator
Sample C# condition
Meaning of C# condition
Equality operators
== x == y x is equal to y
!= x != y x is not equal to y
3.9 Decision Making: Equality and Relational Operators (Cont.)
2
Standard algebraic equality and relational operators
C# equality or relational operator
Sample C# condition
Meaning of C# condition
Relational operators
> x > y x is greater than y
< x < y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y
Fig. 3.25 | Equality and relational operators. (Part 2 of 2.)
3
3.6 Decision Making: Equality and Relational Operators
• The if structure– Used to make a decision based on the truth of the condition• True: a statement is performed• False: the statement is skipped over
– The start of an if statement should not end in a semicolon (;)
– Fig. 3.18 lists the equality and rational operators• There should be no spaces separating the operators
4
3.6 Decision Making: Equality and Relational Operators
Standard algebraic equality operator or relational operator
C# equality or relational operator
Example of C# condition
Meaning of C# condition
Equality operators == x == y x is equal to y != x != y x is not equal to y Relational operators > > x > y x is greater than y < < x < y x is less than y >= x >= y x is greater than or equal to
y <= x <= y x is less than or equal to y Fig. 3.18 Equality and relational operators.
5
1 // Fig. 3.19: Comparison.cs2 // Using if statements, relational operators and equality3 // operators.4 5 using System;6 7 class Comparison8 {9 static void Main( string[] args )10 {11 int number1, // first number to compare12 number2; // second number to compare13 14 // read in first number from user15 Console.Write( "Please enter first integer: " );16 number1 = Int32.Parse( Console.ReadLine() );17 18 // read in second number from user19 Console.Write( "\nPlease enter second integer: " );20 number2 = Int32.Parse( Console.ReadLine() );21 22 if ( number1 == number2 )23 Console.WriteLine( number1 + " == " + number2 );24 25 if ( number1 != number2 )26 Console.WriteLine( number1 + " != " + number2 );27 28 if ( number1 < number2 )29 Console.WriteLine( number1 + " < " + number2 );30 31 if ( number1 > number2 )32 Console.WriteLine( number1 + " > " + number2 );33
34 if ( number1 <= number2 )35 Console.WriteLine( number1 + " <= " + number2 );36 37 if ( number1 >= number2 )38 Console.WriteLine( number1 + " >= " + number2 );39 40 } // end method Main41 42 } // end class Comparison
Please enter first integer: 2000 Please enter second integer: 10002000 != 10002000 > 10002000 >= 1000
Please enter first integer: 1000 Please enter second integer: 20001000 != 20001000 < 20001000 <= 2000
Please enter first integer: 1000 Please enter second integer: 10001000 == 10001000 <= 10001000 >= 1000
7
3.6 Decision Making: Equality and Relational Operators
Operators Associativity Type () left to right parentheses * / % left to right multiplicative + - left to right additive < <= > >= left to right relational == != left to right equality = right to left assignment Fig. 3.20 Precedence and associativity of operators discussed in this
chapter.
8
1 // Fig. 3.26: 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# application
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
• Figure 3.26 uses six if statements to compare two integers entered by the user.
Outline
Comparison.cs
(1 of 3 )
Fig. 3.26 | Comparing integers using if statements, equality operatorsand relational operators. (Part 1 of 3).
9
18 // prompt user and read second number
19 Console.Write( "Enter second integer: " );
20 number2 = Convert.ToInt32( Console.ReadLine() );
21
22 if ( number1 == number2 )
23 Console.WriteLine( "{0} == {1}", number1, number2 );
24
25 if ( number1 != number2 )
26 Console.WriteLine( "{0} != {1}", number1, number2 );
27
28 if ( number1 < number2 )
29 Console.WriteLine( "{0} < {1}", number1, number2 );
30
31 if ( number1 > number2 )
32 Console.WriteLine( "{0} > {1}", number1, number2 );
33
34 if ( number1 <= number2 )
35 Console.WriteLine( "{0} <= {1}", number1, number2 );
Compare number1 and number2 for equality.
Outline
Comparison.cs
(2 of 3 )
Fig. 3.26 | Comparing integers using if statements, equality operatorsand relational operators. (Part 2 of 3).
10
36
37 if ( number1 >= number2 )
38 Console.WriteLine( "{0} >= {1}", number1, number2 );
39 } // end Main
40 } // end class Comparison Enter first integer: 42 Enter second integer: 42 42 == 42 42 <= 42 42 >= 42 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
Outline
Comparison.cs
(3 of 3 )
Fig. 3.26 | Comparing integers using if statements, equality operatorsand relational operators. (Part 3 of 3).
11
3.9 Decision Making: Equality and Relational Operators (Cont.)
• If the condition in an if statement is true, the statement associated with that if statement executes.
• An if statement always begins with keyword if, followed by a condition in parentheses.
• An if statement expects one statement in its body.
Common Programming Error 3.7Forgetting the left and/or right parentheses for thecondition in an if statement is a syntax error—theparentheses are required.
12
3.9 Decision Making: Equality and Relational Operators (Cont.)
Common Programming Error 3.8Reversing the operators !=, >= and <=, as in =!, => and =<, can result in syntax or logic errors.Common Programming Error 3.9It is a syntax error if the operators ==, !=, >= and <= contain spaces between their symbols, as in = =, ! =, > = and < =, respectively.Good Programming Practice 3.12Indent an if statement’s body to make it stand out and to enhance application readability.
13
3.9 Decision Making: Equality and Relational Operators (Cont.)
Common Programming Error 3.10Placing a semicolon immediately after the right parenthesis of the condition in an if statement is normally a logic error. Good Programming Practice 3.13Place no more than one statement per line in an application. This format enhances readability.Good Programming Practice 3.14A lengthy statement can 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 until the end of the statement.
14
5.3 Pseudocode • Pseudocode is similar to every day English, but it is not an actual computer programming language.
• It helps you “think out” an application before attempting to write it.
• A carefully prepared pseudocode application can easily be converted to a corresponding C# application.
15
5.4 Control Structures• Normally, statements are executed one after the other in sequential execution.
• Various C# statements enable you to specify the next statement to execute. This is called transfer of control.
• Structured applications are clearer, easier to debug and modify, and more likely to be bug free.
16
5.4 Control Structures (Cont)• An activity diagram models the workflow of a software system (Fig. 5.1).
• Activity diagrams are composed of symbols such as action-state symbols, diamonds, small circles and notes.
• Transition arrows represent the flow of the activity.
• The solid circle represents the activity’s initial state.
• The solid circle surrounded by a hollow circle represents the final state.
17
5.4 Control Structures (Cont)
Fig. 5.1 | if else double-selection statement UML activity diagram.
18
5.4 Control Structures (Cont)• Single-entry/single-exit control statements make it easy to build applications.
• Control statements are “attached” to one another by connecting the exit point of one to the entry point of the next.
• This procedure is called control-statement stacking.
• Control-statement nesting allows a control statement to appear inside another control statement.
19
5.5 if Single-Selection Statementif grade is greater than or equal to 60
display “Passed”• The preceding pseudocode if statement may be writtenin C# as:
if ( grade >= 60 ) Console.WriteLine( "Passed" );
• Note that the C# code corresponds closely to the pseudocode.
20
5.5 if Single-Selection Statement (Cont.)
• Figure 5.2 illustrates the single-selection if statement.
• The diamond, or decision symbol indicates that a decision is to be made.
• The workflow will continue along a path determined by the symbol’s associated guard conditions.
Fig. 5.2 | if single-selection statement UML activity diagram.
21
5.6 if…else Double-Selection Statement• The if…else double-selection statement
allows you to specify an action to perform when the condition is true and a different action when the condition is false:
if grade is greater than or equal to 60display “Passed”
elsedisplay “Failed”
• The preceding if…else pseudocode statement can be written in C# as
if ( grade >= 60 ) Console.WriteLine( "Passed" );else Console.WriteLine( "Failed" );
22
5.6 if…else Double-Selection Statement (Cont.)
Good Programming Practice 5.1Indent both body statements of an if…else statement.
Good Programming Practice 5.2If there are several levels of indentation, each level should beindented the same addi tional amount of space.
23
5.6 if…else Double-Selection Statement (Cont.)
• Figure 5.3 illustrates the flow of control in the if…else statement.
• The symbols in the UML activity diagram represent action states and a decision.
Fig. 5.3 | if…else double-selection statement UML activity diagram.
24
• The conditional operator (?:) can be used in place of an if…else statement.
Console.WriteLine( grade >= 60 ? "Passed" : "Failed" );
– The first operand is a boolean expression that evaluates to trueor false.– The second operand is the value if the expression is true– The third operand is the value if the expression is false. `
5.6 if…else Double-Selection Statement (Cont.)
25
Good Programming Practice 5.3Conditional expressions are more difficult to read thanif…else statements and should be used to replace onlysimple if else statements that choose between two values.
Good Programming Practice 5.4When a conditional expression is inside a larger expression,it’s good practice to parenthesize the conditional expressionfor clarity. Adding parentheses may also prevent operatorprecedence problems that could cause syntax errors.
5.6 if…else Double-Selection Statement (Cont.)
26
• An application can test multiple cases with nested if…else statements:
if grade is greater than or equal to 90 display “A”
else if grade is greater than or equal to 80
display “B” else
if grade is greater than or equal to 70 display “C”
else if grade is greater than or equal to 60 display “D” else display “F”
5.6 if…else Double-Selection Statement (Cont.)
27
• This pseudocode may be written in C# asif ( grade >= 90 )
Console.WriteLine( "A" );else if ( grade >= 80 ) Console.WriteLine( "B" ); else if ( grade >= 70 ) Console.WriteLine( "C" ); else if ( grade >= 60 ) Console.WriteLine( "D" ); else Console.WriteLine( "F" );
5.6 if…else Double-Selection Statement (Cont.)
28
• Most C# programmers prefer to use else if: if ( grade >= 90 ) Console.WriteLine( "A" );else if ( grade >= 80 ) Console.WriteLine( "B" );else if ( grade >= 70 ) Console.WriteLine( "C" );else if ( grade >= 60 ) Console.WriteLine( "D" );else Console.WriteLine( "F" );
5.6 if…else Double-Selection Statement (Cont.)
29
• The C# compiler always associates an else with the immediately preceding if unless told to do otherwise by the placement of braces ({ and }).
• This behavior can lead to what is referred to as the dangling-else problem.
5.6 if…else Double-Selection Statement (Cont.)
30
if ( x > 5 ) if ( y > 5 ) Console.WriteLine( "x and y are > 5" );else Console.WriteLine( "x is <= 5" );
• The compiler actually interprets the statement as:if ( x > 5 )
if ( y > 5 ) Console.WriteLine( "x and y are > 5" ); else Console.WriteLine( "x is <= 5" );
5.6 if…else Double-Selection Statement (Cont.)
31
• To have the nested if else statement execute as it was intended, write it as follows:
if ( x > 5 ){
if ( y > 5 ) Console.WriteLine( "x and y are > 5" );
}else
Console.WriteLine( "x is <= 5" );
5.6 if…else Double-Selection Statement (Cont.)
32
• A set of statements contained within a pair of braces ({ and }) is called a block:
if ( grade >= 60 ) Console.WriteLine( "Passed" );
else{
Console.WriteLine( "Failed" ); Console.WriteLine( "You must take this course
again." );}
• Without the braces, the last statement would execute regardless of whether the grade was less than 60.
5.6 if…else Double-Selection Statement (Cont.)
33
• A logic error has its effect at execution time.– A fatal logic error causes an application to fail and terminate prematurely.
– A nonfatal logic error allows an application to continue executing.
5.6 if…else Double-Selection Statement (Cont.)
34
5.6 if…else Double-Selection Statement (Cont.)
Common Programming Error 5.1Forgetting braces that delimit a block can lead to syntaxerrors or logic errors in an application.
Good Programming Practice 5.5Always using braces in an if…else (or other) statementhelps prevent their accidental omission. Some programmerstype the beginning and ending braces of blocks before typingthe individual statements within them.
35
5.6 if…else Double-Selection Statement (Cont.)
Common Programming Error 5.2Placing a semicolon after the condition in an if or if…elsestatement leads to a logic error in single-selection ifstatements and a syntax error in double-selection if…elsestatements (when the if-part contains an actual bodystatement).