Computing with C# and the.NET Framework Chapter 4 More Control Structures and Types ©2003, 2011 Art Gittleman
Figure 4.1 Conditional Operators
Figure 4.2 Evaluating an example of a conditional AND expression
Figure 4.3 Evaluating an example of a conditional OR expression
Figure 4.4 Evaluating a logical complement expression
Figure 4.5 Evaluating a conditional AND expression
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 code True False Test1? Test2? Test1 true code Test2 true code True 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 format switch (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 for (initialize; test; update) for_statement int sum = 0; for (int i = 1; i <= 4; i++) sum += i;
initializei = 1 test1 <= 4 is true execute bodysum += 1(result: sum = = 1) updatei++(result: i = 2) test2 <= 4 is true execute bodysum += 2(result: sum = = 3) updatei++(result: i = 3) test3 <= 4 is true execute bodysum += 3(result: sum = = 6) updatei++(result: i + 4) test4 <= 4 is true execute bodysum += 4(result: sum = = 10) updatei++(result: i = 5) test5 <= 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 int sum = 0; for (int i = 1; i < 10; i += 2) sum += i;
Figure 4.20 A for statement for the sum 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 index int 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 statement while (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 characters Use single quote ‘a’, ‘B’ Internally 16 bits ASCII table in appendix Unicode represents thousands of characters We use ASCII for English \ is the escape character, gives special meaning to next character
\\backlash Special Character Meaning \nnewline, move to the start of the next line \ttab \bbackspace \rreturn, move to the start of the current line \"double quote \nnewline, 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 to 9,223,372,036,854,775,807 long bigNumber = L; sbyte, byte, short, ushort -- integer types, special uses float -- decimal type, 7 place accuracy float size = 4.56F; uint, ulong, decimal
Enumerations Provides convenient names for values enum 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 squared Math.Sqrt(2.0) returns Math.Sqrt(16.0) returns 4.0
Maximum and Minimum Math.Max(3, 4) returns 4 Math.Max(17.32, ) returns Math.Max(-9, -11) returns -9 Math.Min(3, 4) returns 3 Math.Min(17.32, ) returns Math.Min(-9, -11) returns -11
Absolute value Math.Abs(x) = x, if x >= 0 = -x, if x < 0 Math.Abs(-10) returns 10 Math.Abs(12.34) returns 12.34
Floor and Ceiling Math.Floor(25.194) returns 25.0 Math.Floor( ) returns Math.Ceiling(25.194) returns 26.0 Math.Ceiling( ) returns
Trigonometric and Exponential Math.Sin( Math.PI ) returns 0.0 Math.Cos(Math.PI) returns -1.0 Math.Tan(Math.PI/4) returns 1 Math.Exp(1.0) returns Math.Exp(2.0) returns Math.Log(Math.E) returns 1 Math.Log(10.0) returns
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;