Presentation is loading. Please wait.

Presentation is loading. Please wait.

Week 6: THE C# LANGUAGE Flow Control. Slide 2 Data Types Boolean Byte (0 to 255) Char Date String Decimal Object Short (-32,768 to 32,767) Integer (-2,147,483,648.

Similar presentations


Presentation on theme: "Week 6: THE C# LANGUAGE Flow Control. Slide 2 Data Types Boolean Byte (0 to 255) Char Date String Decimal Object Short (-32,768 to 32,767) Integer (-2,147,483,648."— Presentation transcript:

1 Week 6: THE C# LANGUAGE Flow Control

2 Slide 2 Data Types Boolean Byte (0 to 255) Char Date String Decimal Object Short (-32,768 to 32,767) Integer (-2,147,483,648 to 2,147,483,647) Long (larger whole numbers) Single (floating point accuracy to 6 digits) Double (floating point accuracy to 14 points)

3 Slide 3 Data Types – Memory Usage Boolean – 1 bytes Byte – 1 byte Char – 2 bytes Date – 8 bytes String – varies Decimal – 16 bytes Object – Short – 2 bytes Integer – 4 bytes Long – 8 bytes Single – 4 bytes Double – 8 bytes

4 Slide 4 Data Types – Prefixes Boolean – bln Byte – byt Char – chr Date – dat String – str Decimal – dec Object – depends on type of object Short – sht Integer – int Long – lng Single – sng Double – dbl

5 Slide 5 Declaration Statements Declare Variables int intNumberOfStudents ; CONST used to declare Named Constants Const single sngDISCOUNT_RATE = 0.2f; Declaration includes Name, follow Naming Convention Rules Data Type Required Value for Constants Optional Initial Value for Variables

6 Slide 6 Type-Declaration Characters Append single character to the end of the Constant's Value to indicate the Data Type Decimal – m Single – F Double Const Single sngDISCOUNT_RATE = 0.2F;

7 Slide 7 Declaration Examples string strName, strSSN ; int intAge; decimal decPayRate ; decimal decTax=0.1M ; bool blnInsured ; long lngPopulation ; decimal decDT, decCD, decCR; decimal decHour, decSumSal, decDiemTB, decSum=0; decimal decTax = 0.12M, decHSLuong=3.16M; const decimal decDISCOUNT_RATE = 0.15M;

8 Slide 8 Scope Declaring & Naming (*) Publicg prefix Declare in General Declarations as Public Module/Privatem prefix Declare in Module’s General Declarations as Private Localno prefix required Declare in Event Procedures String gstrName ; String mstrName; String strName ;

9 Slide 9 Scope Public Available to all modules and procedures of Project Module/Private (Form) Can be used in any procedure on a specific Form, but is not visible to other Forms Initialized 1 st time the Form is loaded Local Available only to the procedure it is declared in Initialized every time the Procedure runs Block (not used until later in this course) Available only to the block of code inside a procedure it is declared in Initialized every time the Procedure runs

10 Slide 10 Declaring Local Level Variables Example Local Level Variables

11 Slide 11 Declaring Module Level Variables Example Module - Level Variables and Constants

12 Slide 12 Declaring Block Level Variables Example int a,b; if (a > b) { int max; max = a; } else { int max1; max1=max Được không?? max1 = b; } Block Level Variables

13 Slide 13 Math Class Methods (p 192) The Math class Allows the user to perform common math calculations Using methods ClassName.MethodName( argument1, arument2, … ) Constants Math.PI = 3.1415926535… Math.E = 2.7182818285…

14 Slide 14 9:06:37 AM Math Class Methods

15 Slide 15 Math Class Methods

16 Slide 16 Compound Assignment Operators Assignment operators Can reduce code x += 2 is the same as x = x + 2 Can be done with all the math operators ++, -=, *=, /=, and %=

17 Slide 17 Assignment Operators

18 Slide 18 Increment and Decrement Operators Increment operator Used to add one to the variable x++ Same as x = x + 1 Decrement operator Used to subtract 1 from the variable y--

19 Increment and Decrement Operators Pre-increment vs. post-increment x++ or x-- Will perform an action and then add to or subtract one from the value ++x or --x Will add to or subtract one from the value and then perform an action Windows Programming 1 Slide 19

20 Slide 20 Increment and Decrement Operators

21 Slide 21 Increment and Decrement Operators

22 Slide 22 Format Code

23 Slide 23 Example lblCommission.Text = string.Format("{0:C}",decCommission);

24 Slide 24 Format Code

25 Slide 25 Logical and Conditional Operators Operators Logical AND (&) Conditional AND (&&) Logical OR (|) Conditional OR (||) Logical exclusive OR or XOR (^) Logical NOT (!) Can be avoided if desired by using other conditional operators Used to add multiple conditions to a statement

26 Slide 26 Logical and Conditional Operators

27 Slide 27 Logical and Conditional Operators

28 Slide 28 Structured Programming Summary

29 Slide 29 Mathematical Examples Thứ tự thưc hiện

30 Slide 30 Control Structures Program of control Program performs one statement then goes to next line Sequential execution Different statement other than the next one executes Selection structure  The if and if/else statements  The goto statement  No longer used unless absolutely needed  Causes many readability problems Repetition structure  The while and do/while loops (chapter 5)  The for and foreach loops (chapter 5)

31 Slide 31 Control Structures add grade to total add 1 to counter total = total + grade; counter = counter + 1; Fig. 5.1Flowcharting C#’s sequence structure.

32 Slide 32 if Selection Structure The if structure Causes the program to make a selection Chooses based on conditional Any expression that evaluates to a bool type True: perform an action False: skip the action Single entry/exit point Require no semicolon in syntax

33 Slide 33 if Selection Structure Fig. 5.3Flowcharting a single-selection if structure. do something conditions true false

34 Slide 34 if/else selection structure The if/else structure Alternate courses can be taken when the statement is false Rather than one action there are two choices Nested structures can test many cases Structures with many lines of code need braces ({) Can cause errors  Fatal logic error  Nonfatal logic error

35 Slide 35 if/else Selection Structure Fig. 5.4Flowcharting a double-selection if / else structure. Conditions do something do something else falsetrue

36 Slide 36 Conditional Operator (?:) C#’s only ternary operator Similar to an if/else structure The syntax is: boolean value ? if true : if false Console.WriteLine( grade >= 60 ? "Passed" : "Failed" );

37 Slide 37 Loops Repeating a series of instructions Each repetition is called an iteration Types of Loops Do Use when the number of iterations is unknown For Use when the number of iterations known

38 Slide 38 while Repetition Structure Fig. 4.5Flowcharting the while repetition structure. true false do something conditions

39 Slide 39 for Repetition Structure The for repetition structure Syntax: for (Expression1, Expression2, Expression3) Expression1 = names the control variable  Can contain several variables Expression2 = loop-continuation condition Expression3 = incrementing/decrementing  If Expression1 has several variables, Expression3 must have several variables accordingly  ++counter and counter++ are equivalent

40 Slide 40 9:06:37 AM for Repetition Structure for (int counter = 1; counter <= 5; counter++ ) Initial value of control variableIncrement of control variable Control variablenameFinal value of control variable for keyword Loop-continuation condition Fig. 5.3Components of a typical for header.

41 Slide 41 for Repetition Structure counter++ Establish initial value of control variable. Determine if final value of control variable has been reached. counter <= 10 Console.WriteLine ( counter * 10 ); true false int counter = 1 Body of loop (this may be multiple statements) Increment the control variable. Fig. 5.4Flowcharting a typical for repetition structure.

42 Slide 42 switch Multiple-Selection Structure switch ( ) { Case Giá trị 1 : [ code to run] break; Case Giá trị 2 : [ code to run] break; [default ] [code to run]] } If expression=value in constant list If expression values in any of the preceding constant lists

43 Slide 43 Flocharting Switch Multiple Selection Structure. Case a: Actions abreak; Case b: Actions bbreak; Case n: Action nbreak; default break; true false

44 Slide 44 SwitchCase - Numeric Value Example 1 switch ( intScore) { case 100: lblMsg.Text="Excellent Score"; break; case 99: lblMsg.Text="Very Good"; break; case 79: lblMsg.Text="Excellent Score"; break; default: lblMsg.Text="Improvement Needed"; break; }

45 Slide 45 9:06:37 AM do/while Repetition Structure The while loops vs. the do/while loops Using a while loop Condition is tested The the action is performed Loop could be skipped altogether Using a do/while loop Action is performed Then the loop condition is tested Loop must be run though once Always uses brackets ({) to prevent confusion

46 Slide 46 do/while Repetition Structure true false action(s) condition Fig. 5.13Flowcharting the do / while repetition structure.

47 Slide 47 9:06:37 AM MessageBox Object Use Show Method of MessageBox to display special type of window Arguments of Show method Message to display Optional Title Bar Caption Optional Button(s) Optional Icon

48 Slide 48 9:06:37 AM MessageBox Syntax MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon) The MessageBox is an Overloaded Method Overloading – ability to call different versions of a procedure based on the number and data types of the arguments passed to that procedure The number and data types of the arguments expected by a procedure are called Signatures There are multiple Signatures to choose from Arguments must be included to exactly match one of the predefined Signatures

49 Slide 49 9:06:37 AM MessageBoxIcon Constants

50 Slide 50 9:06:37 AM MessageBoxButton

51 Slide 51 Ex DialogResult dl; dl= MessageBox.Show( "Are you sure exit ? ", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dl == DialogResult.Yes) Close();

52 Week 6: THE C# LANGUAGE More Variable

53 Value types and reference types The.NET type system defines two categories of data type Value types Values stored on the stack Derived from System.ValueType Examples of built-in framework value types: Byte, Int16, Int32, Int64, Single, Double, Decimal, Char, Boolean C# has built-in types which are aliases for these: byte, short, int, long, float, double, decimal, char, bool Object Oriented Software Development 53

54 Value types and reference types Reference types Objects stored in the heap References stored on the stack Types derived from System.Object Examples of reference types: String (C# alias is string) all classes, including classes in your project arrays (see later) delegates (see later) Object Oriented Software Development 54

55 Boxing and unboxing Boxing Converting value type to reference type Unboxing Converting reference type to value type We will look again at boxing and type conversions later Object Oriented Software Development 4. C# data types, objects and references 55

56 Creating value types There are two kinds of value type in.NET struct Similar to a class, but stored as a value type Local variable of struct type will be stored on the stack Built-in values types, e.g. Int32, are structs enum An enumeration type Consists of a set of named constants Object Oriented Software Development 56

57 struct Example in TimeSheet.cs - rewrite TimeSheet as a struct rather than a class struct can contain instance variables, constructors, properties, methods Can’t explicitly declare default constructor Compiler generates default constructor Object Oriented Software Development 57

58 struct Instance can be created without new key word With class, this would create a null reference With struct, this creates instance with fields set to default values This explicitly calls default constructor Object Oriented Software Development 58

59 Method call with struct parameter Revisit earlier example with TimeSheet as a struct Main creates TimeSheet struct instance and passes it as a parameter to RecordOvertime Parameter contains a copy of the struct A copy of whole struct placed on stack Object Oriented Software Development 4. C# data types, objects and references 59

60 struct vs. class TimeSheet example is a small struct, but structs can have large numbers of instance variables Passing large structs as parameters can use a lot of stack memory On the other hand, creating objects on the heap is expensive in terms of performance compared to creating structs No definitive rules, but take these factors into account when deciding Object Oriented Software Development 4. C# data types, objects and references 60

61 enum enum is a good way of storing and naming constant values Enum has an underlying data type int by default in example, Days.Sat, Days.Sun, Days.Mon... represent values 0,1, 2,... can set values explicitly Object Oriented Software Development 4. C# data types, objects and references 61

62 enum example Previously indicated pay rate with boolean value isWeekend Replace this with enum, which allows more than simply true/false Object Oriented Software Development 62

63 enum example Change parameter in RecordOvertime to type PayRate Object Oriented Software Development 63

64 enum example Pass in enumeration value to method Always refer to value by name, don’t need to know or use underlying value Object Oriented Software Development 64

65 Warning! Classes, objects, instance variables, methods, references are fundamental OO concepts Value types (struct, enum) and properties are specific to the way in which.NET interprets the OO programming model Object Oriented Software Development 65


Download ppt "Week 6: THE C# LANGUAGE Flow Control. Slide 2 Data Types Boolean Byte (0 to 255) Char Date String Decimal Object Short (-32,768 to 32,767) Integer (-2,147,483,648."

Similar presentations


Ads by Google