Upload
others
View
18
Download
0
Embed Size (px)
Citation preview
Module 2.4: Control Statements: Part II
Xianrong (Shawn) Zheng
Spring 2017
IT 374 C# and Applications/IT695 C# Data Structures
IT374/ IT695 1
Essentials of Counter-Controlled Iteration for Iteration Statement do…while Iteration Statement switch Multiple Selection Statement break and continue Statements Logical Operators
Outline
IT374/ IT695 2
The elements of counter-controlled iteration:1. a control variable (or loop counter),2. the control variable’s initial value,3. the control variable’s increment that’s applied during
each iteration of the loop,4. the loop-continuation condition that determines if
looping should continue.
Essentials of Counter-Controlled Iteration
IT374/ IT695 3
IT374/ IT695 4
C# provides the for iteration statement, which specifies the elements of counter-controlled iteration in a single line of code.
for Iteration Statement
IT374/ IT695 5
IT374/ IT695 6
IT374/ IT695 7
The general format of the for statement isFor (initialization; loopContiuationCondition; increment){
statement}
If the initialization expression in the for header declares the control variable, the control variable can be used onlyin that for statement ─ it will not exist outside it. This restricted use of the name of the control variable is known as the variable’s scope.
for Iteration Statement (Cont.)
IT374/ IT695 8
All three expressions in a for header are optional. If the loopConinuationCondition is omitted, C# assumes that it’s always true, thus creating an infinite loop.
You can omit the initialization expression if the app initializes the control variable before the loop ─ in this case, the scope of the control variable will not be limited to the loop.
You can omit the increment expression if the app calculates the increment with statements in the loop’s body or if no increment is needed.
for Iteration Statement (Cont.)
IT374/ IT695 9
The initialization, loop-continuation condition and increment portions of a for statement can contain arithmetic expressions.
Apps frequently display the control variable value or use it in calculations in the loop body, but this use is not required. The control variable is commonly used to control iteration without being mentioned in the body of the for.
for Iteration Statement (Cont.)
IT374/ IT695 10
IT374/ IT695 11
The initialization and increment expressions can be comma-separated lists that enable you to use multiple initialization expressions or multiple increment expressions.
App: Summing Even Integers
IT374/ IT695 12
IT374/ IT695 13
The next app uses the for statement to compute compound interest.
C# treats numeric literals like 0.05 as type double. Similarly, C# treats whole-number literals like 7 and 1000 as type int ─ unlike double values, int values can be assigned to decimal variables. When principle is initialized to 1000, the int value 1000 is promoted to type decimal implicitly ─ no cast is required.
App: Compound-Interest Calculations
IT374/ IT695 14
IT374/ IT695 15
IT374/ IT695 16
IT374/ IT695 17
Many classes also provide methods to perform common tasks that do not require specific objects ─ they must be called using a class name. Such methods are called static methods. You’ve used several static methods of class Console ─ methods Write, WriteLine and ReadLine.
You call a static method by specifying the class name followed by the member-access operator(.) and the method name, as in ClassName.MethodName (arguments)
App: Compound-Interest Calculations (Cont.)
IT374/ IT695 18
C# does not include an exponentiation operator, so we use class Math’s static method Pow to perform the compound-interest calculation. The expression Math.Pow (x, y) calculates the value of x raised to the yth power.
C# will not implicitly convert double to a decimal type, or vice versa, because of the possible loss of information in either conversion.
App: Compound-Interest Calculations (Cont.)
IT374/ IT695 19
The interpolation expression {year, 4} formats the year. The integer 4 after the comma indicats that the value output should be displayed with a field width of 4 ─ that is, WriteLine displays the value with at least four character positions.
If the value to be output is fewer than four character positions wide, the value is right-aligned in the field by default.
If the value to be output were more than four character positions wide, the field width would be extended to the right to accommodate the entire value.
App: Compound-Interest Calculations (Cont.)
IT374/ IT695 20
Similarly, the interpolation expression {amount, 20:C} formats the amount as currency (C) right-aligned in a field of at least 20 characters. To left align value, simply use a negative field width.
Due to the imprecise nature of floating-point numbers, type double is preferred over type float, because double variables can represent floating-point numbers more precisely.
App: Compound-Interest Calculations (Cont.)
IT374/ IT695 21
The do…while statement tests the loop-continuation condition after executing the loop’s body; therefore, the body always executes at least once.
do…while Iteration Statement
IT374/ IT695 22
IT374/ IT695 23
IT374/ IT695 24
C# provides the switch multiple-selection statement to perform different actions based on the possible values of an expression, known as the switch expression. Each action is associated with one or more of the switch expression’s possible values. These are specified as constant integral expressions or a constant string expression.
switch Multiple-Selection Statement
IT374/ IT695 25
A constant integral expression is any expression involving character and integer constants that evaluates to an integer value ─ i.e., values of type sbyte, byte, short, ushort, int, uint, long, ulong and char, or a constant from an enum type.
A constant string expression is any expression composed of string literals or const string variables that always results in the same string.
switch Multiple-Selection Statement
IT374/ IT695 26
IT374/ IT695 27
IT374/ IT695 28
IT374/ IT695 29
IT374/ IT695 30
IT374/ IT695 31
IT374/ IT695 32
The notation Ctrl + z means to hold down the Ctrl key and tap the z key when typing in a Command Prompt. Ctrl + z is the Windows key sequence for typing the end-of-file indicator. This is one way to inform an app that there’s no more data to input. If Ctrl + z is entered while the app is awaiting input with a ReadLine method, null is returned.
The end-of-file indicator is a system-dependent keystroke combination. On many non-Windows systems, end-of-file is entered by typing Ctrl + d.
Windows typically displays the characters ^Z in a Command Prompt when the end-of-file indicator is typed.
switch Multiple-Selection Statement (Cont.)
IT374/ IT695 33
The switch statement consists of a block that contains a sequence of case labels and an optional default label. These are used in this example to determine which counter to increment based on the grade.
The app attempts to match the value of the switch expression with one of the case labels.
The switch expression in line 31 performs integer division, which truncates the fractional part of the result.
The break statement (line 39) causes program control to proceed with the first statement after the switch (line 51).
switch Multiple-Selection Statement (Cont.)
IT374/ IT695 34
Listing case labels consecutively in this manner with no statements between them enables the cases to perform the same set of statements.
Each case can have multiple statements. The switch statement differs from other control statements in that it does not require braces around multiple statements in each case.
switch Multiple-Selection Statement (Cont.)
IT374/ IT695 35
If no match occurs between the switch expression’s value and a case label, the statements after the default label execute.
If no match occurs and the switch does not contain a default label, program control simply continues with the first statement (if there’s one) after the switch statement.
switch Multiple-Selection Statement (Cont.)
IT374/ IT695 36
C# is different from other programming languages ─ after the statement in a case, you’re required to include a statement that terminates the case, such as a break, a return or a throw; otherwise, a compilation error occurs.
switch Multiple-Selection Statement (Cont.)
IT374/ IT695 37
IT374/ IT695 38
In the switch statements cases, constant integral expressions can be character constants ─ specific characters in single quotes, such as ‘A’, ‘7’ or ‘$’ ─ which represent the integer values of characters.
A string constant (or string literal) is a sequence of characters in double quotes, such as “Welcome to C# Programming!” or a const string variable.
The expression in each case also can be a constant ─ a value which does not change for the entire app. Constants are declared with the keyword const.
switch Multiple-Selection Statement (Cont.)
IT374/ IT695 37
Strings can be used in switch expressions, and string literals can be used in case labels.
Class AutoPolicy Case Study: strings in switch Statements
IT374/ IT695 40
IT374/ IT695 41
IT374/ IT695 42
IT374/ IT695 43
IT374/ IT695 44
The break statement, when executed in a while, for, do…while, switch, or foreach, causes immediate exit from the loop or switch. Execution continues with the first statement after the control statement.
break and continue Statements
IT374/ IT695 45
IT374/ IT695 46
IT374/ IT695 47
The continue statement, when executed in a while, for, do…while, switch, or foreach, skips the remaining statements in the loop body and proceeds with the next iteration of the loop.
In while and do…while statements, the app evaluates the loop-continuation test immediately after the continue statement executes.
In a for statement, the increment expression normally executes next, then the app evaluates the loop-continuation test.
break and continue Statements (Cont.)
IT374/ IT695 48
IT374/ IT695 49
IT374/ IT695 50
C# provides logical operators to enable you to form more complex conditions by combining simple conditions.
Suppose that we wish to ensure at some point in an app that two conditions are both true before we choose a certain path of execution. In this case, we can use the &&(conditional AND) operator.
Logical Operators
IT374/ IT695 51
IT374/ IT695 52
Now suppose we wish to ensure that either or both of two conditions are true before we choose a certain path of execution. In this case, we use the || (conditional OR) operator.
Logical Operators (Cont.)
IT374/ IT695 53
IT374/ IT695 54
The parts of an expression containing && or || operators are evaluated only until it’s known whether the condition is true or false. This feature of conditional AND andconditional OR expression is called short-circuit evaluation.
The Boolean logical AND (&) and Boolean logical inclusive OR (|) operators work identically to the && (conditional AND) and || (conditional OR) operators, with one exception ─ the Boolean logical operators alwaysevaluate both of their operands (i.e., they do not perform short-circuit evaluation)
Logical Operators (Cont.)
IT374/ IT695 55
A complex condition contains the boolean logical exclusive OR (^) operator (also called the logical XOR operator) is true if and only if one of its operands is true and the other is false. If both operands are true or false, the entire condition is false.
Logical Operators (Cont.)
IT374/ IT695 56
IT374/ IT695 57
The ! (logical negation or not) operator enables you to “reverse” the meaning of a condition. It is a unary operator that has only a single condition as an operand.
Logical Operators (Cont.)
IT374/ IT695 58
IT374/ IT695 59
IT374/ IT695 60
IT374/ IT695 61
IT374/ IT695 62
IT374/ IT695 63
IT374/ IT695 64
IT374/ IT695 65
IT374/ IT695 66
Any form of control ever needed in a C# app can be expressed in terms of sequence, the if statement (selection) and the while statement (iteration). These can be combined in only two ways ─ stacking and nesting.
Structured-Programming Summary
IT374/ IT695 66
IT374/ IT695 68
IT374/ IT695 69
IT374/ IT695 70
IT374/ IT695 71
IT374/ IT695 72
IT374/ IT695 73
IT374/ IT695 74
6.9, 6.10, 6.14, and 6.19 (pp. 232-190 of the textbook)
Exercises
IT374/ IT695 66