Document 16518075

advertisement
Computing with C#
and the .NET Framework
Chapter 3
Software Engineering with
Control Structures
Operator
Symbol
Meaning
Example
<
less than
31 < 25
is false
<=
less than or equal to
464 <= 7213
is true
>
greater than
-98 > -12
is false
>=
greater than or equal to
9 >= 99
is false
==
equal to
9 == 12 + 12
is false
!=
not equal to
292 != 377
is true
Figure 3.1 Java relational and equality operators
The if Statement
Type bool Two values, true and false
if (condition)
if_true_statement
The condition is a bool expression. If it is
true then the if_true_statement will be
executed
if (x >2)
y = x + 17;
Entry
int item1 = 25;
int item2 = 12;
Item2 = item1+15;
Exit
Figure 3.2 The sequence control flow
condition
true
if_true_statement
false
Figure 3.3 Control flow for the if statement
int hours = int.parse(Console.ReadLine());
Hour
s
>40
False
True
Console.WriteLine(“You “ +
“worked overtime this week”)
Console.WriteLine(
“you worked {0} hours”,
hours);
Figure 3.4 Control Flow for Example 3.2
The if-else statement
Choose between two alternatives
if (condition)
if ( x <= 20)
if_true_statement
x += 5;
else
else
if_false_statement
x+=2;
True
if_true_statement
Condition
False
if_false_statement
Figure 3.5 Flow chart for the if-else statement
Blocks
Group a sequence of statements inside braces
{
x = 5;
y = -8;
z = x*y;
}
May use a block in an if or if-else statement
True
Z <= 10
False
x = 2;
y = 7;
Figure 3.6 Flow chart for if statement with block, step 1
True
Z <=
10
x = 2;
False
y = 7;
Figure 3.7 Flow chart if statement with block, step 2
Scientific Notation
Small or large numbers are hard to read
Use exponents instead
3.937E-8 instead of .00000003937
5.88E12 instead of 5,880,000,000,000
E or e
E12 or E+12
Type double
Provides about 16 decimal places
double length = 173.24E5; // exponent
double height 1.83;
// fixed
+,-,*,/ operators
Formatted Output
{0:E}
Scientific default (three decimal
places)
{0:F2} Fixed-point, two decimal places
{O:G} General, default (same as {0})
Uses scientific notation if exponent is less
than -4 or if the exponent is greater or equal
to the number of significant digits in the
number
Original expression
2.54
+
361
After Conversion
2.54
+
361.0
Figure 3.8 Conversion of mixed-mode expression
while statement
Provides repetition
while (condition)
while_true_statement
while (x < 10)
x += 2;
If x = 5, then x becomes 7, 9 before loop stops
while (x < 10)
x -= 4;
//does not terminate if x starts at 5
False
Condition
True
while_true_statement
Figure 3.9 Flow chart for the while loop
Read the quantity of scores;
while(count < quantity) {
Read the next score;
Add the score to the total so far;
Increment the count of scores;
}
Display the quantity and the total;
Figure 3.10 Pseudocode for the sum of test scores problem
Debugging
Read the code carefully to determine where
the error might be located
Add WriteLine statements to get more
information
Test thoroughly
Use a debugger if available
Download