Presentation is loading. Please wait.

Presentation is loading. Please wait.

STATEMENTS AND FLOW OF EXECUTION CHAPTER 11 OF APRESS A PROGRAMMERS GUIDE TO C SHARP 5.0.

Similar presentations


Presentation on theme: "STATEMENTS AND FLOW OF EXECUTION CHAPTER 11 OF APRESS A PROGRAMMERS GUIDE TO C SHARP 5.0."— Presentation transcript:

1 STATEMENTS AND FLOW OF EXECUTION CHAPTER 11 OF APRESS A PROGRAMMERS GUIDE TO C SHARP 5.0

2 SELECT STATEMENTS If - ifstatement evaluate to an expression of type bool If - ifstatement evaluate to an expression of type bool

3 Switch - have often been error-prone; it is just too easy to inadvertently omit a break statement at the end of a case Switch - have often been error-prone; it is just too easy to inadvertently omit a break statement at the end of a case

4 C# KEYWORDS

5 AVOIDING CONFLICTS If you really want to use an identifier that clashes with a keyword, you can do so by qualifying it with the @prefix. If you really want to use an identifier that clashes with a keyword, you can do so by qualifying it with the @prefix.

6 CONTEXTUAL KEYWORDS Some keywords are contextual, meaning they can also be used as identifiers - without an @symbol Some keywords are contextual, meaning they can also be used as identifiers - without an @symbol

7 LITERALS, PUNCTUATORS, AND OPERATORS Literals – 12 and 30 are examples of literals Literals – 12 and 30 are examples of literals Punctuators – help demarcate the structure of the program Punctuators – help demarcate the structure of the program { } - statement block { } - statement block ; - terminates a statement ; - terminates a statement Operator – transforms and combines expressions Operator – transforms and combines expressions. () * =. () * =

8 COMMENTS // - single line // - single line /* */ - multiple line /* */ - multiple line

9 TYPE BASICS A type defines the blueprint for a value A type defines the blueprint for a value Literals 12 and 30 Literals 12 and 30 Variable of type int for x Variable of type int for x All values in C# are instances of a type. All values in C# are instances of a type.

10 PREDEFINED TYPE EXAMPLES Predefined types are types that are specially supported by the compiler. The int type is a predefined type for representing the set of integers that fit into 32 bits of memory, from − 2 31 to 2 31 − 1. Predefined types are types that are specially supported by the compiler. The int type is a predefined type for representing the set of integers that fit into 32 bits of memory, from − 2 31 to 2 31 − 1. String is another predefined C# type. String is another predefined C# type. Bool is another predefined type with two possible values: true and false. Bool is another predefined type with two possible values: true and false.

11 CUSTOM TYPE EXAMPLES

12 Members of a type Members of a type A type contains data members and function members. A type contains data members and function members. The data member of UnitConverter is the field called ratio. The data member of UnitConverter is the field called ratio. The function members of UnitConverter are the Convert method and the UnitConverter’s constructor. The function members of UnitConverter are the Convert method and the UnitConverter’s constructor.

13 Symmetry of predefined types and custom types Symmetry of predefined types and custom types A beautiful aspect of C# is that predefined types and custom types have few differences. A beautiful aspect of C# is that predefined types and custom types have few differences. The predefined int type serves as a blueprint for integers. The predefined int type serves as a blueprint for integers. It holds data—32 bits - and provides function members that use that data, such as ToString. It holds data—32 bits - and provides function members that use that data, such as ToString. UnitConverter type acts as a blueprint for unit conversions. It holds data - the ratio - and provides function members to use that data. UnitConverter type acts as a blueprint for unit conversions. It holds data - the ratio - and provides function members to use that data.

14 Constructor and Instantiation Constructor and Instantiation The new operator creates instances of a custom type. UnitConverter feetToInchesConverter = new UnitConverter (12); The new operator creates instances of a custom type. UnitConverter feetToInchesConverter = new UnitConverter (12); Constructor is called to perform initialization. Constructor is called to perform initialization.

15 Instance versus static members Instance versus static members The data members and function members that operate on the instanceof the type are called instance members. The data members and function members that operate on the instanceof the type are called instance members. The UnitConverter’s Convertmethod and the int’s ToString method are examples of instance members. The UnitConverter’s Convertmethod and the int’s ToString method are examples of instance members. By default, members are instance members. By default, members are instance members. Data members and function members that don’t operate on the instance of the type, but rather on the type itself, must be marked as static. Data members and function members that don’t operate on the instance of the type, but rather on the type itself, must be marked as static.

16 The public keyword The public keyword The publickeyword exposes members to other classes. The publickeyword exposes members to other classes.

17 CONVERSIONS Can be either implicit or explicit Can be either implicit or explicit Example Example

18 Implicit conversions are allowed when both of the following are true: Implicit conversions are allowed when both of the following are true: The compiler can guarantee they will always succeed. The compiler can guarantee they will always succeed. No information is lost in conversion. No information is lost in conversion. Explicit conversions are required when one of the following is true: Explicit conversions are required when one of the following is true: The compiler cannot guarantee they will always succeed. The compiler cannot guarantee they will always succeed. Information may be lost during conversion. Information may be lost during conversion.

19 PREDEFINED TYPE TAXONOMY

20 NUMERIC TYPES

21 Numeric Literals Numeric Literals Integral literals – decimal and hexadecimal Integral literals – decimal and hexadecimal int x = 127; int x = 127; long y = 0x7F; long y = 0x7F; Real literal – decimal and/or exponential notation Real literal – decimal and/or exponential notation double d = 1.5; double d = 1.5; double million = 1E06 double million = 1E06

22 Numeric literal type inference Numeric literal type inference By default, the compiler infers a numeric literal to be either double or an integral type: By default, the compiler infers a numeric literal to be either double or an integral type: If the literal contains a decimal point or the exponential symbol (E), it is a double. If the literal contains a decimal point or the exponential symbol (E), it is a double. Otherwise, the literal’s type is the first type in this list that can fit the literal’s value: int, uint, long, and ulong Otherwise, the literal’s type is the first type in this list that can fit the literal’s value: int, uint, long, and ulong

23 Numeric suffixes Numeric suffixes

24 The suffixes U and L are rarely necessary, because the uint, long, and ulong types can nearly always be either inferred or implicitly converted from int: The suffixes U and L are rarely necessary, because the uint, long, and ulong types can nearly always be either inferred or implicitly converted from int: long i = 5; long i = 5; The D suffix is technically redundant, in that all literals with a decimal point are inferred to be double. The D suffix is technically redundant, in that all literals with a decimal point are inferred to be double. Double x = 4.0 Double x = 4.0

25 The F and M suffixes are the most useful and should always be applied when specifying float or decimal literals. The F and M suffixes are the most useful and should always be applied when specifying float or decimal literals. float f = 4.5F; //will not compile without the F float f = 4.5F; //will not compile without the F The same principle is true for a decimal literal: decimal d = − 1.23M; // Will not compile without the M suffix. The same principle is true for a decimal literal: decimal d = − 1.23M; // Will not compile without the M suffix.

26 NUMERIC CONVERSIONS Integral to integral conversion Integral to integral conversion Integral conversions are implicit when the destination type can represent every possible value of the source type. Otherwise, an explicit conversion is required Integral conversions are implicit when the destination type can represent every possible value of the source type. Otherwise, an explicit conversion is required Floating-point to floating-point conversions Floating-point to floating-point conversions A float can be implicitly converted to a double, since a double can represent every possible value of a float. The reverse conversion must be explicit. A float can be implicitly converted to a double, since a double can represent every possible value of a float. The reverse conversion must be explicit.

27 Floating-point to integral conversions Floating-point to integral conversions All integral types may be implicitly converted to all floating-point types: int i = 1; float f = i; All integral types may be implicitly converted to all floating-point types: int i = 1; float f = i; The reverse conversion must be explicit: int i2 = (int)f; The reverse conversion must be explicit: int i2 = (int)f;

28 Decimal conversions Decimal conversions All integral types can be implicitly converted to the decimal type, since a decimal can represent every possible C# integral value. All integral types can be implicitly converted to the decimal type, since a decimal can represent every possible C# integral value. All other numeric conversions to and from a decimal type must be explicit. All other numeric conversions to and from a decimal type must be explicit.

29 ARITHMETIC OPERATORS The arithmetic operators (+, -, *, /, %) are defined for all numeric types except the 8- and 16-bit integral types: The arithmetic operators (+, -, *, /, %) are defined for all numeric types except the 8- and 16-bit integral types:

30 INCREMENT AND DECREMENT OPERATORS The increment and decrement operators (++, −− ) increment and decrement numeric types by 1. The increment and decrement operators (++, −− ) increment and decrement numeric types by 1.

31 SPECIALIZED INTEGRAL OPERATIONS Integral Division Integral Division Division operations on integral types always truncate remainders (round towards zero). Dividing by a variable whose value is zero generates a runtime error (a DivideByZeroException): Division operations on integral types always truncate remainders (round towards zero). Dividing by a variable whose value is zero generates a runtime error (a DivideByZeroException):

32 Integral overflow Integral overflow No exception is thrown and the result exhibits “wraparound” behavior No exception is thrown and the result exhibits “wraparound” behavior

33 Integral arithmetic overflow check operators Integral arithmetic overflow check operators The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions. The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions. The checked operator tells the runtime to generate an OverflowException rather than overflowing silently when an integral expression or statement exceeds the arithmetic limits of that type. The checked operator tells the runtime to generate an OverflowException rather than overflowing silently when an integral expression or statement exceeds the arithmetic limits of that type. The checked operator affects expressions with the ++, −−, +, − (binary and unary), *, /, and explicit conversion operators between integral types. The checked operator affects expressions with the ++, −−, +, − (binary and unary), *, /, and explicit conversion operators between integral types.

34

35 Disable checking Disable checking

36 Overflow checking for constant expressions Overflow checking for constant expressions Regardless of the /checked compiler switch, expressions evaluated at compile time are always overflow-checked—unless you apply the unchecked operator: int x = int.MaxValue + 1; // Compile-time error int y = unchecked (int.MaxValue + 1); // No errors Regardless of the /checked compiler switch, expressions evaluated at compile time are always overflow-checked—unless you apply the unchecked operator: int x = int.MaxValue + 1; // Compile-time error int y = unchecked (int.MaxValue + 1); // No errors

37 Bitwise operators Bitwise operators

38 8- AND 16-BIT INTEGRALS The 8- and 16-bit integral types are byte, sbyte, short, and ushort. The 8- and 16-bit integral types are byte, sbyte, short, and ushort. These types lack their own arithmetic operators, so C# implicitly converts them to larger types as required. These types lack their own arithmetic operators, so C# implicitly converts them to larger types as required. This can cause a compile-time error when trying to assign the result back to a small integral type: short x = 1, y = 1; short z = x + y; // Compile-time error short z = (short) (x + y); //OK This can cause a compile-time error when trying to assign the result back to a small integral type: short x = 1, y = 1; short z = x + y; // Compile-time error short z = (short) (x + y); //OK

39 SPECIAL FLOAT AND DOUBLE VALUES

40 DOUBLE VERSUS DECIMAL

41 REAL NUMBER ROUNDING ERRORS float and double internally represent numbers in base 2. float and double internally represent numbers in base 2. Base 10 will not be represented precisely. Base 10 will not be represented precisely. For example: For example: float tenth = 0.1f; // Not quite 0.1 float tenth = 0.1f; // Not quite 0.1 float one = 1f; float one = 1f; Console.WriteLine (one - tenth * 10f); // − 1.490116E-08 Console.WriteLine (one - tenth * 10f); // − 1.490116E-08 Decimal works in base 10 and so can precisely represent numbers expressible in base 10 (as well as its factors, base 2 and base 5) Decimal works in base 10 and so can precisely represent numbers expressible in base 10 (as well as its factors, base 2 and base 5)

42 BOOLEAN TYPE AND OPERATORS C#’s booltype (aliasing the System.Booleantype) is a logical value that can be assigned the literal trueor false. C#’s booltype (aliasing the System.Booleantype) is a logical value that can be assigned the literal trueor false.

43 EQUALITY AND COMPARISON OPERATORS == and != test for equality and inequality of any type, but always return a bool value. Value types typically have a very simple notion of equality: == and != test for equality and inequality of any type, but always return a bool value. Value types typically have a very simple notion of equality: int x = 1; int x = 1; int y = 2; int y = 2; int z = 1; int z = 1; Console.WriteLine (x == y); // False Console.WriteLine (x == y); // False Console.WriteLine (x == z); // True Console.WriteLine (x == z); // True

44

45 CONDITIONAL OPERATORS The && and ||operators test for and and or conditions. They are frequently used in conjunction with the ! operator, which expresses not. The && and ||operators test for and and or conditions. They are frequently used in conjunction with the ! operator, which expresses not. Example static bool UseUmbrella (bool rainy, bool sunny, bool windy) { Example static bool UseUmbrella (bool rainy, bool sunny, bool windy) { return !windy && (rainy || sunny); }

46 The &&and ||operators short-circuit evaluation when possible. The &&and ||operators short-circuit evaluation when possible. If it is windy, the expression (rainy || sunny) is not even evaluated. If it is windy, the expression (rainy || sunny) is not even evaluated. Short-circuiting is essential in allowing expressions such as the following to run without throwing a NullReferenceException: if (sb != null && sb.Length > 0)... Short-circuiting is essential in allowing expressions such as the following to run without throwing a NullReferenceException: if (sb != null && sb.Length > 0)... The & and |operators also test for and and or conditions: The & and |operators also test for and and or conditions: return !windy & (rainy | sunny);

47 STRINGS AND CHARACTERS

48 String Type String Type string a1 = "\\\\server\\fileshare\\helloworld.cs"; string a1 = "\\\\server\\fileshare\\helloworld.cs"; string a2 = @"\\server\fileshare\helloworld.cs"; string a2 = @"\\server\fileshare\helloworld.cs"; String concatenation String concatenation String s = “a” + “b”; String s = “a” + “b”;

49 OPERATOR TABLE

50

51

52

53 STATEMENTS Declaration statements Declaration statements string someWord = "rosebud"; string someWord = "rosebud"; int someNumber = 42; int someNumber = 42; bool rich = true, famous = false; bool rich = true, famous = false; Constants Constants const double c = 2.99792458E08; const double c = 2.99792458E08; c += 10; // Compile-time Error c += 10; // Compile-time Error

54 Scoping static void Main() { int x; { int y; int x; // Error - x already defined } { int y; // OK - y not in scope } Console.Write (y); // Error - y is out of scope } Scoping static void Main() { int x; { int y; int x; // Error - x already defined } { int y; // OK - y not in scope } Console.Write (y); // Error - y is out of scope }

55 SELECTION STATEMENTS Selection statements (if, switch) Selection statements (if, switch) Conditional operator (?:) Conditional operator (?:) Loop statements (while, do..while, for, foreach) Loop statements (while, do..while, for, foreach)

56 The if statement The if statement An if statement executes a statement if a bool expression is true. For example: if (5 < 2 * 3) Console.WriteLine ("true"); // true An if statement executes a statement if a bool expression is true. For example: if (5 < 2 * 3) Console.WriteLine ("true"); // true The statement can be a code block: if (5 < 2 * 3) { Console.WriteLine ("true"); Console.WriteLine ("Let's move on!"); } The statement can be a code block: if (5 < 2 * 3) { Console.WriteLine ("true"); Console.WriteLine ("Let's move on!"); }

57 The else clause The else clause An if statement can optionally feature an else clause: if (2 + 2 == 5) Console.WriteLine ("Does not compute"); else Console.WriteLine ("False"); // False An if statement can optionally feature an else clause: if (2 + 2 == 5) Console.WriteLine ("Does not compute"); else Console.WriteLine ("False"); // False Within an else clause, you can nest another if statement: if (2 + 2 == 5) Console.WriteLine ("Does not compute"); else if (2 + 2 == 4) Console.WriteLine ("Computes"); // Computes Within an else clause, you can nest another if statement: if (2 + 2 == 5) Console.WriteLine ("Does not compute"); else if (2 + 2 == 4) Console.WriteLine ("Computes"); // Computes

58 The switch statement static void ShowCard(int cardNumber) { switch (cardNumber) { case 13: Console.WriteLine ("King"); break; case 12: Console.WriteLine ("Queen"); break; case 11: Console.WriteLine ("Jack"); break; case − 1: // Joker is − 1 goto case 12; // In this game joker counts as queen default: // Executes for any other cardNumber Console.WriteLine (cardNumber); break; } } The switch statement static void ShowCard(int cardNumber) { switch (cardNumber) { case 13: Console.WriteLine ("King"); break; case 12: Console.WriteLine ("Queen"); break; case 11: Console.WriteLine ("Jack"); break; case − 1: // Joker is − 1 goto case 12; // In this game joker counts as queen default: // Executes for any other cardNumber Console.WriteLine (cardNumber); break; } }

59 Here are the options: Here are the options: break(jumps to the end of the switch statement) break(jumps to the end of the switch statement) goto case x(jumps to another case clause) goto case x(jumps to another case clause) goto default(jumps to the default clause) goto default(jumps to the default clause) Any other jump statement—namely, return, throw, continue, or goto label Any other jump statement—namely, return, throw, continue, or goto label

60 ITERATION STATEMENTS while and do-while loops while and do-while loops While loops repeatedly execute a body of code while a bool expression is true. The expression is tested before the body of the loop is executed. While loops repeatedly execute a body of code while a bool expression is true. The expression is tested before the body of the loop is executed. For example: int i = 0; while (i < 3) { Console.WriteLine (i); i++; } For example: int i = 0; while (i < 3) { Console.WriteLine (i); i++; } OUTPUT: 0 1 2 OUTPUT: 0 1 2

61 Do-while loop Do-while loop int i = 0; do { Console.WriteLine (i); i++; } while (i < 3);

62 For loops For loops for (initialization-clause; condition-clause; iteration-clause) statement-or-statement-block

63 foreach loops foreach loops Enumerable object Enumerable object

64 EXERCISES TO BE PASSED 1. Print your birth year in one column. For example, if you were born in 1982, your output should look like the following: 1 9 8 2

65 2. Create an application that displays the following patterns. You may use any character of your choice to construct the pattern.

66 3. Write a program to calculate and display your average and grade.Allow the user to enter five scores. After values are entered, and the average calculated, test the result to determine whether an A, B, C, D, or F should be recorded. The scoring rubric is as follows: A—90–100; B—80–89; C—70– 79; D—60–69; F < 60.


Download ppt "STATEMENTS AND FLOW OF EXECUTION CHAPTER 11 OF APRESS A PROGRAMMERS GUIDE TO C SHARP 5.0."

Similar presentations


Ads by Google