650 likes | 750 Views
Week 6: THE C# LANGUAGE. Flow Control. 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)
E N D
Week 6: THE C# LANGUAGE Flow Control
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)
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
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
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
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;
Declaration Examples stringstrName, strSSN ; intintAge; decimaldecPayRate ; decimaldecTax=0.1M ; boolblnInsured ; 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;
Scope Declaring & Naming (*) • Public g prefix • Declare in General Declarations as Public • Module/Private m prefix • Declare in Module’s General Declarations as Private • Local no prefix required • Declare in Event Procedures • String gstrName ; String mstrName; • String strName ;
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 1st 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
Declaring Local Level Variables Example Local Level Variables
Module - Level Variables and Constants Declaring Module Level Variables Example
Block Level Variables Block Level Variables 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; }
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…
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 %=
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--
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
Example • lblCommission.Text = string.Format("{0:C}",decCommission);
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
Thứ tự thưc hiện Mathematical Examples
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)
add grade to total total = total + grade; add 1 to counter counter = counter + 1; Control Structures Fig. 5.1 Flowcharting C#’s sequence structure.
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
conditions do something true false if Selection Structure Fig. 5.3 Flowcharting a single-selection if structure.
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
false true Conditions do something else do something if/else Selection Structure Fig. 5.4 Flowcharting a double-selection if/else structure.
Conditional Operator (?:) • 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" );
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
conditions true do something false while Repetition Structure Fig. 4.5 Flowcharting the while repetition structure.
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
for keyword Control variable name Final value of control variable for ( int counter = 1; counter <= 5; counter++ ) Initial value of control variable Increment of control variable Loop-continuation condition for Repetition Structure Fig. 5.3 Components of a typical for header.
for Repetition Structure Establish initial value of control variable. int counter = 1 Determine if final value of control variable has been reached. true Console.WriteLine counter <= 10 counter++ ( counter * 10 ); Increment the control variable. false Body of loop (this may be multiple statements) Fig. 5.4 Flowcharting a typical for repetition structure.
switch Multiple-Selection Structure switch(<Biểu Thức>) { CaseGiá trị 1 : [ code to run] break; CaseGiá 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
true Case a: Actions a break; false true Case b: Actions b break; false true Case n: Action n break; false true default break; Flocharting Switch Multiple Selection Structure.
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; }
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
action(s) true condition false do/while Repetition Structure Fig. 5.13 Flowcharting the do/while repetition structure.
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
MessageBox Syntax • 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 MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon)