computing with c# and the.net framework chapter 4 more control structures and types ©2003, 2011 art...

Post on 18-Jan-2018

219 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

Figure 4.1 Conditional Operators

TRANSCRIPT

Computing with C#and the .NET Framework

Chapter 4More Control Structures and Types

©2003, 2011 Art Gittleman

Symbol Meaning Example && conditional AND (age > 20) && (age < 35) || conditional OR (height > 78.5) || (weight > 300)

Figure 4.1 Conditional Operators

age age > 20 age < 35 age > 20 && age < 35 10 false true false 25 true true true 40 true false false

Figure 4.2 Evaluating an example of a conditional AND expression

height weight height > 78.5 weight > 300 (height>78.5) || (weight>300)

62 125 false false false

80 250 true false true

72 310 false true true

80 325 true true true

Figure 4.3 Evaluating an example of a conditional OR expression

A !A true false false true

Figure 4.4 Evaluating a logical complement expression

A B A && B true true true true false false false (don't care) false

Figure 4.5 Evaluating a conditional AND expression

A B A || B true (don't care) true false true true false false false

Figure 4.6 Evaluating a condition OR expression

Figure 4.7 Operator precedence*

Highest

NOT! !multiplicative * / %

additive + -relational < > <= >=equality == !=conditional AND &&conditional OR ||assignment = += -= *= /=

%=Lowest

if (score >= 60 && score < 80)

Console.WriteLine

("Score " + score + " receives a C");

else

Console.WriteLine

("Score " + score + " receives a B or an A");

Figure 4.8 If-else statement to choose between two alternatives

Figure 4.9 Nested if-else statement to choose among three alternatives

if (score >= 60 && score < 80) Console.WriteLine("Score " + score + " receives a C");else if (score >=80 && score < 90) Console.WriteLine("Score " + score + " receives a B");else Console.WriteLine("Score " + score + " receives an A"); 

Figure 4.10 Improved version of Figure 4.9

if (score >= 60 && score < 80) Console.WriteLine("Score " + score + " receives a C");else if (score >= 80 && score < 90) Console.WriteLine("Score " + score + " receives a B");else if (score >= 90 && score <= 100) Console.WriteLine("Score " + score + " receives an A");

Nested if format if ( Is it the first alternative? ){ First alternative code}else if ( Is it the second alternative? ) { Second alternative code} ...else if ( Is it the last alternative? ) { Last alternative code}else { Code when none of the above alternatives is true}

Figure 4.12 Flow chart for nested if-else statements

Last?

Last false code

...

Last true codeTrueFalse

False

Test1?

Test2?

Test1 true code

Test2 true code

True

TrueFalse

False

Figure 4.13 Incorrect attempt to pair an else with an if

if (score >= 60) if (score >= 80) Console.WriteLine("You got a B or an A");else Console.WriteLine("You got a D or an F"); // Wrong pairing

// else does not pair with first if

Figure 4.14 Corrected pairing of else and if

if (score >= 60) if (score >= 80) Console.WriteLine("You got a B or an A"); else Console.WriteLine("You got a C"); // Correct pairing

// Pair else with nearest if

Figure 4.15 Figure 4.13 rewritten as an if-else with nested if

if (score >= 60) { if (score >= 80) Console.WriteLine("You got a B or an A");}else // Paired to first 'if' Console.WriteLine("You got a D or an F");

switch formatswitch (test_expression) { case expression1: statement1; break; case expression2: statement2; break; ..... default: default_statement; break;}

Figure 4.16 An example of a switch statement

switch(mark) { case 0: case 1: case 2: case 3: case 4: System.out.println("F"); break; case 5: System.out.println("D"); break; case 6: case 7: System.out.println("C"); break; case 8: System.out.println("B"); break; case 9: case10: System.out.println("A"); break; default:System.out.println("Incorrect score");}

Figure 4.17 A for statement pattern and example for the sum 1+2+3+4

for (initialize; test; update) for_statement

int sum = 0;for (int i = 1; i <= 4; i++) sum += i;

initialize i = 1

test 1 <= 4 is true

execute body sum += 1 (result: sum = 0 + 1 = 1)

update i++ (result: i = 2)

test 2 <= 4 is true

execute body sum += 2 (result: sum = 1 + 2 = 3)

update i++ (result: i = 3)

test 3 <= 4 is true

execute body sum += 3 (result: sum = 3 + 3 = 6)

update i++ (result: i + 4)

test 4 <= 4 is true

execute body sum += 4 (result: sum = 6 + 4 = 10)

update i++ (result: i = 5)

test 5 <= 4 is false

Figure 4.18 Trace of execution of the for loop of Figure 4.17

Figure 4.19 A for statement for the sum 1+3+5+7+9

int sum = 0;for (int i = 1; i < 10; i += 2) sum += i;

Figure 4.20 A for statement for the sum 4+3+2+1

int sum = 0;for (int i = 4; i >= l; i--) sum += i;

Figure 4.21 Declaring an index variable before the for loop

int i; // declare loop indexint sum = 0;for (i = 4; i >= 1; i--) // initialize loop index sum += i;...i += 17; // use variable i

Figure 4.22 Syntax for the do statement

do statementwhile (condition) ;

Figure 4.23 Pseudocode for example 4.5 enhancement

do { Compute balance as in Example 4.5 Ask the user -- Repeat or Quit?} while (User chooses to repeat);

char type

Represents charactersUse single quote ‘a’, ‘B’Internally 16 bitsASCII table in appendixUnicode represents thousands of charactersWe use ASCII for English\ is the escape character, gives special meaning to

next character

\\backlash

 

SpecialCharacter

Meaning

\n newline, move to the start of the next line

\t tab

\b backspace

\r return, move to the start of the current line

\" double quote

\n newline, move to the start of the next line

Figure 4.24 Escape sequences for special characters

Additional primitive types

long -9,223,372,036,854,775,808 to9,223,372,036,854,775,807

long bigNumber = 12345678987L;sbyte, byte, short, ushort -- integer types, special

usesfloat -- decimal type, 7 place accuracyfloat size = 4.56F;uint, ulong, decimal

Enumerations

Provides convenient names for valuesenum Color {Red, Green, Blue}Declare variables

Color c = Color.Red;Test

if ( c == Color.Green) // do something

Powers and Roots

Math.Pow(2.0,3.0) returns 8.0 // 2 cubed Math.Pow(3.0,2.0) returns 9.0 // 3 squaredMath.Sqrt(2.0) returns

1.4142135623730951 Math.Sqrt(16.0) returns 4.0

Maximum and Minimum

Math.Max(3, 4) returns 4Math.Max(17.32, 5.8567) returns 17.32Math.Max(-9, -11) returns -9Math.Min(3, 4) returns 3Math.Min(17.32, 5.8567) returns 5.8567Math.Min(-9, -11) returns -11

Absolute value

Math.Abs(x) = x, if x >= 0 = -x, if x < 0Math.Abs(-10) returns 10Math.Abs(12.34) returns 12.34

Floor and Ceiling

Math.Floor(25.194) returns 25.0Math.Floor(-134.28) returns -135.0Math.Ceiling(25.194) returns 26.0Math.Ceiling(-134.28) returns -134.0

Trigonometric and Exponential

Math.Sin( Math.PI ) returns 0.0Math.Cos(Math.PI) returns -1.0Math.Tan(Math.PI/4) returns 1Math.Exp(1.0) returns 2.718281828459045Math.Exp(2.0) returns 7.38905609893065Math.Log(Math.E) returns 1Math.Log(10.0) returns 2.302585092994046

Figure 4.25 Iterative problem-solving process

Formulate the problem;do { Develop pseudocode; Implement pseudocode in Java program; Test program;while (More subproblems to refine);

Figure 4.26 Top-level Pseudocode

do [ Display the menu; Get the user's choice; Execute the user's choice;} while (user does not choose to quit);

Figure 4.27 Pattern for a menu-driven application

do { choice = IO.GetInt("Choose: \n" + "1. Convert from meters to yds,ft,in \n" + "2. Convert from yds,ft,in to meters \n" + "3. Quit: "); int choice = Io.readInt("Enter your choice, 1, 2 or 3"); switch (choice) { case 1: MetricToEnglish(); break; case 2: EnglishToMetric(); break; case 3: Console.WriteLine("Bye, Have a nice day"); break; }} while (choice != 3);

Figure 4.28 Pseudocode for the MetricToEnglish method

Input the number of meters, x, to convert;Convert x meters to y yards;Separate y into yInteger yards and yFraction yards;Convert yFraction yards to f feet.Separate f into fInteger feet and fFraction feet.Convert fFraction feet to i inches.Display the output.

Figure 4.29 Refinement:Display the output

if (yInteger > 0) if (yInteger <= 1) Display yInteger yard; else Display yInteger yards;if (fInteger > 0) if (fInteger <= 1) Display fInteger foot; else Display fInteger feet;if (i >0) if (i <= 1) Display i inch; else Display i inches;if (yInteger == 0 && fInteger == 0 && i == 0) Display 0 yards;

Figure 4.30 Pseudocode for the EnglishToMetric method

Input yards, feet, and inches to convert;Convert to inches;Convert inches to meters;Output the result;

top related