Ngôn ngữ C#

Preview:

DESCRIPTION

Ngôn ngữ C#. Content. Cấu trúc chương trình C# Kiểu dữ liệu, từ khoá, định danh biến, hằng… Chuyển đổi kiểu Console I/O Tham số ref, out, param Lệnh phân nhánh switch, lệnh nhảy Lệnh lặp for, while, do while, foreach Mảng 1 chiều, đa chiều Kiểu enumeration. Cấu trúc chương trình C#. - PowerPoint PPT Presentation

Citation preview

Ngôn ngữ C#Ngôn ngữ C#

ContentContent

1. Cấu trúc chương trình C#

2. Kiểu dữ liệu, từ khoá, định danh biến, hằng…

3. Chuyển đổi kiểu

4. Console I/O

5. Tham số ref, out, param

6. Lệnh phân nhánh switch, lệnh nhảy

7. Lệnh lặp for, while, do while, foreach

8. Mảng 1 chiều, đa chiều

9. Kiểu enumeration

2

Cấu trúc chương trình C#Cấu trúc chương trình C#

3

using <namespace sử dụng>

…namespace <Tên Namespace>{

[Khóa truy xuất] class <Tên lớp> {

public static void Main(){

}

// thành viên khác …

}

// lớp khác …

using <namespace sử dụng>

…namespace <Tên Namespace>{

[Khóa truy xuất] class <Tên lớp> {

public static void Main(){

}

// thành viên khác …

}

// lớp khác …

Cấu trúc chương trình C#Cấu trúc chương trình C# using: làm code gọn hơn, không cần phải dùng tên của

namspace using System.

namespace của chương trình: ko bắt buộc. Dùng để hạn chế phạm vi của một tên, làm cho tên này chỉ có ý nghĩa trong vùng đã định nghĩa.

Giả sử có một người nói Tùng là một kỹ sư, từ kỹ sư phải đi kèm với một lĩnh vực nhất định nào đó, vì nếu không thì chúng ta sẽ không biết được là anh ta là kỹ sư cầu đường, cơ khí hay phần mềm. Khi đó một lập trình viên C# sẽ bảo rằng Tùng là CauDuong.KySu phân biệt với CoKhi.KySu hay hanMem.KySu. Namespace trong trường hợp này là CauDuong, CoKhi, PhanMem sẽ hạn chế phạm vi của những từ theo sau.

4

Cấu trúc chương trình C#Cấu trúc chương trình C#

Nếu ko có namespace namespace mặc định ko tên Namespace có thể chứa: struct, interface, delegate, enum Trường hợp đơn giản nhất: 1 lớp, 1 file cs và namespace mặc

định

5

Cấu trúc chương trình C#Cấu trúc chương trình C#

class: kiểu trong C# được định nghĩa là một lớp (class), và các thể hiện riêng của từng lớp được gọi là đối tượng (object). Tối thiểu có 1 lớp chứa hàm entry point Main của chương trình.

Phương thức chính là các hàm được định nghĩa trong lớp. Các phương thức này chỉ ra rằng các hành động mà lớp có thể làm được cùng với cách thức làm hành động đó.

public static void Main(): đầu vào của lớp (entry point) và được CRL gọi đầu tiên khi thực thi.

6

Data TypeData Type

Bao gồm Lớp đối tượng object ký tự char Chuỗi string Số nguyên có dấu sbyte, short, int, long Số nguyên không dấu byte, ushort, uint, ulong Số thực float, double, decimal Kiểu logic bool

Alias của các lớp dữ liệu trong .NET sstring System.SString iint System.IInt32 oobject System.OObject

7

Data TypeData Type

Sử dụng kiểu dữ liệu Định nghĩa trước (C#)

Built-in : int, long, string, object… Chương trình định nghĩa

Class, struct, enum… Person, Student, Employee…

8

Data Type

Built-inBuilt-in User definedUser defined

The built-in value typeThe built-in value type

NameName CTS TypeCTS Type SizeSize RangeRangesbyte System.SByte 8 -128..127short System.Int16 16 (-32768 .. 32767)int Sytem. Int32 32 -231..231-1long Sytem. Int64 64 -263..263-1byte System.SByte 8 0..255ushort System.UInt16 16 (0 .. 65535)uint System.UInt32 32 0..232-1ulong System.UInt64 64 0..264-1float System.Single 32 x p x t 3,4E - 38 đ n 3,4E+38ấ ỉ ừ ế

double System.Double 64 1,7E-308 đ n 1,7E+308ế

decimal System.Decimal 128 Có đ chính xác đ n 28 con sộ ế ố

bool System.Boolean Ki u true/falseể

char System.Char 16 Ký t unicodeự

9

The built-in reference typeThe built-in reference type

object: Sytem.Object Kiểu dữ liệu gốc, cha của tất cả các kiểu dữ liệu trong C#

object o = new object();

string: Sytem.String Chuỗi ký tự Unicode

string s1 = “Hi”; string s2 = “Hi Hi “; string s = s1 + s2;

10

The built-in reference typeThe built-in reference type

11

Phân loại kiểu dữ liệuPhân loại kiểu dữ liệu

12

Value typeValue type Reference type

Reference type

Data type

int num;long count;

Object obj = new Object();String str = “reference type”;

Phân loại theo cách thức lưu trữ dữ liệu

Value TypeValue Type

Chứa giá trị trực tiếp Không thể null

Phải chứa giá trị xác định Bao gồm

Primitive type double, char, int, float

Enum struct

13

int i = 59;

5959i

7.837.83x

5959a

double x = 7.83;int a = i;

Reference typeReference type

Chỉ tới nơi chứa dữ liệu Có thể null

null: không chỉ tới bất kỳ đâu

Bao gồm Lớp (class)

string, object

Giao diện (interface) Mảng (array) Đại diện (delegate)

14

string s1 = "Hello";

"Hello""Hello"

"Bye""Bye"s2

s3

s1

string s2 = "Bye";string s3;s3 = s1;

Value type vs. Reference typeValue type vs. Reference type

Characteristic Value type Reference type

Variable hold Value Reference

Allocated Stack Heap

Default Zero Null

Parameter Copy value Copy reference

15

identifieridentifier

Định danh: những từ được đặt ra để đại diện cho mọi thứ dùng trong chương trình Khi đặt định danh: nên có tính gợi nhớ

Tạo ra định danh mới HelloWorld, Program, Perform,… phải khai báo trước khi sử dụng

Dùng định danh có sẵn Console, WriteLine, ReadLine,… phải chỉ ra nơi chứa định danh (namespace)

16

IdentifierIdentifier

Bao gồm chữ cái, chữ số, ký tự gạch dưới Không được bắt đầu bằng chữ số

Chuong_Trinh, x25, z, _abc, XửLý hợp lệ 2abc, Chuong-Trinh, Xu Ly, class không hợp lệ

Phân biệt CHỮ HOA và chữ thường ChuongTrinh và chuongtrinh là khác nhau

Các định danh được khai báo trong cùng phạm vi (scope) không được trùng nhau

Phải khác với từ khóa (dùng “@” khắc phục)

17

KeywordKeyword

abstract const extern in operator sbyte throw virtualas continue false int out sealed true voidbase decimal finally interface override set try volatilebool default fixed internal params short typeof wherebreak delegate float is partial sizeof uint whilebyte do for lock private stackalloc ulong yieldcase double foreach long protected static uncheckedcatch else get namespace public string unsafechar enum goto new readonly struct ushortchecked event if null ref switch usingclass explicit implicit object return this value

Các từ khóa trong C# 2005

18

ConstantConstant

Một hằng là một biến nhưng trị không thay đổi

const int a = 100; // giá trị ko thể thay đổi Hằng bắt buộc phải được gán giá trị lúc khai báo Trị của hằng có thể được tính toán vào lúc biên dịch Hằng bao giờ cũng static

19

ConstantConstant

Ưu điểm Chương trình dễ đọc, khắc phục những con số “magic

number” trong code. Chương trình dễ sửa hơn. Tránh lỗi dễ dàng hơn, trình biên dịch sẽ báo lỗi nếu gán lại

giá trị cho hằng

20

Minh họa sử dụng hằng

21

Định nghĩa hằng

Constant

readonlyreadonly

22

constconst: phải được gán giá trị khi khai báo

readonlyreadonly: ko cần khởi tạo trước, khi gán giá trị thì sau đó ko thay đổi được

Chưa được khởi gán

Ko được thay đổi

VariableVariable

Biến là nơi lưu dữ liệu của chương trình Dữ liệu của biến

Nằm trong bộ nhớ vật lý (physical RAM) Có thể thay đổi giá trị

Phải khai báo trước khi dùng Identifier: tên để đại diện cho biến Data type: dạng lưu trữ dữ liệu của biến

23

Data type identifierData type identifier

VariableVariable

Phạm vi (scope) Được xác định bởi cặp dấu { và } Có thể chứa phạm vi nhỏ hơn

Vị trí khai báo biến Trong thân phương thức: biến cục bộ Trong thân lớp(trong class): thuộc tính

Biến trong C# chỉ có tác dụng trong phạm vi mà nó được khai báo

24

Keyword Description

Public Truy xuất từ bất cứ nơi nào trong chương trình hay từ bất cứ chương trình khác mà tham khảo tới nó.

Private Truy xuất từ bất cứ nơi nào trong lớp chứa nó.

Protected Truy xuất từ bất cứ nơi nào trong lớp chứa nó hay bất cứ lớp nào thừa kế từ lớp này.

Prefix Data Type

bln Boolean

dat Date

dec Decimal

dbl Double-precision

int Integer

lng Long Integer

sng Single-precision

str String

VariablesNguyên tắc đặt tên biến

string strName, strSSN ;int intAge; decimal decPayRate ;decimal decTax=0.1 ;bool blnInsured ;long lngPopulation ;decimal decDT, decCD, decCR;decimal decHour, decSumSal, decDiemTB, decSum=0;decimal decTAX = 0.12, decHSLUONG=3.16;Const decimal decDISCOUNT_RATE = 0.15M;

Note: Constants are named using all uppercase letters EXCEPT the prefix.

Variables

Type castType cast

Ép kiểu: chuyển giá trị từ kiểu này sang kiểu khác Ví dụ

Chuyển từ int qua float và ngược lại Có hai loại

Ép kiểu ngầm định (implicit type-cast) Ép kiểu chỉ định (explicit type-cast)

27

Implicit type castImplicit type cast

Do C# tự thực hiện Không cần lập trình viên can thiệp Xảy ra khi

Ép từ kiểu nhỏ qua kiểu lớn

Ép từ lớp dẫn xuất qua lớp cơ sở

28

int i = 59;double x = i;

string s = "Hello";object o = s;

Implicit type-castImplicit type-cast

From To

sbyte short, int, long, float, double, decimal

byte short, ushort, int, uint, long, ulong, float, double, decimal

short int, long, float, double, decimal

ushort int, uint, long, ulong, float, double, decimal

int long, float, double, decimal

uint long, ulong, float, double, decimal

long, ulong float, double, decimal

float double

char ushort, int, uint, long, ulong, float, double, decimal

29

Explicit type-castExplicit type-cast

Do lập trình viên chỉ định Xảy ra khi

Ép từ kiểu lớn qua kiểu nhỏ: có thể mất giá trị

Ép từ lớp cơ sở qua lớp dẫn xuất

30

double x = 74.86;int i = (int)x; // i = 74

string s = "Hello";object o = s;string s2 = (string)o;

Using Convert classUsing Convert class

Thường dùng khi cần chuyển đổi giữa các kiểu không có liên hệ với nhau

Convert.toDataType(SourceValue) Ví dụ: chuyển từ chuỗi sang số thực

31

string s1 = "56.8";

double x = Convert.ToDouble(s1); // x = 56.8int i = Convert.ToInt32(s2); // i = 95

string s2 = "95";

byte j = Convert.ToByte(x); // j = 56, ít dùng

Console I/OConsole I/O

Để đọc ký tự văn bản từ cửa sổ console Console.Read() giá trị trả về là int

Console.ReadLine() giá trị trả về là string

Để xuất chuỗi ký tự dùng Console.Write() / Console.WriteLine()

32

Console I/OConsole I/O

33

Console I/OConsole I/O

Console.WriteLine()

34

\n: ký tự xuống dòng

Console I/OConsole I/O

35

/ F5

Xuất chuỗiĐọc chuỗi

Chờ đọc 1 dòng, mục đích là dừng màn hình

Addition.cs

1 // Fig. 3.11: Addition.cs

2 // An addition program.

3 using System;

4 class Addition

5 {

6 static void Main( string[] args )

7 {

8 string firstNumber, // first string entered by user

9 secondNumber; // second string entered by user

10 int number1, // first number to add

11 number2, // second number to add

12 sum; // sum of number1 and number2

13 // prompt for and read first number from user as string

14 Console.Write( "Please enter the first integer: " );

15 firstNumber = Console.ReadLine();

16 // read second number from user as string

17 Console.Write( "\nPlease enter the second integer: " );

18 secondNumber = Console.ReadLine();

19 // convert numbers from type string to type int

20 number1 = Int32.Parse( firstNumber );

21 number2 = Int32.Parse( secondNumber );

22 // add numbers

23 sum = number1 + number2;

Addition.cs

Console I/OConsole I/O

Please enter the first integer: 45 Please enter the second integer: 72 The sum is 117.

32 // display results

33 Console.WriteLine( "\nThe sum is {0}.", sum );

34

35 } // end method Main

36

37 } // end class Addition

Console I/OConsole I/O

Boxing & UnboxingBoxing & Unboxing

Kiểu giá trị có thể được chuyển thành kiểu đối tượng

Boxing

Unboxing

38

UnboxingUnboxing

BoxingBoxing

checked & uncheckedchecked & unchecked

39

throws OverFlowException

Operators

Arithmetic Operations

Relational Operators

Assignment Operators

Increment and Decrement Operators

Logical and Conditional Operators

Arithmetic Operations

Notes: Must be written in a straight line There are no exponents Division can vary depending on the variables used

When dividing two integers the result is always rounded down to an integer. To be more exact use a variable that supports decimals

Operator Operation Example

+ Addition 3+7 = 10

- Subtraction 3-7 = -4

* Multiplication 2*3 = 6, 2*2 =4

/ Division 9/3 = 3, 10/3 =3

% Modulus (division's remainder) 9%2 =1

Arithmetic Operations

Operator(s) Operation Order of evaluation (precedence) ( ) Parentheses Evaluated first. If the parentheses are nested,

the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.

*, / or % Multiplication Division Modulus

Evaluated second. If there are several such operators, they are evaluated left to right.

+ or - Addition Subtraction

Evaluated last. If there are several such operators, they are evaluated left to right.

Fig. 3.16 Precedence of arithmetic operators.

Arithmetic Operations

Thứ tự thực hiện

Arithmetic Operations

Fig. 3.17 Order in which a second-degree polynomial is evaluated.

Step 1.

Step 2.

Step 5.

Step 3.

Step 4.

Step 6.

y = 2 * 5 * 5 + 3 * 5 + 7;

2 * 5 is 10 (Leftmost multiplication)

y = 10 * 5 + 3 * 5 + 7;

10 * 5 is 50 (Leftmost multiplication)

y = 50 + 3 * 5 + 7;3 * 5 is 15 (Multiplication before addition)

y = 50 + 15 + 7;

50 + 15 is 65 (Leftmost addition)

y = 65 + 7;

65 + 7 is 72 (Last addition)

y = 72; (Last operation—place 72 into y)

Relational Operators

Standard algebraic equality operator or relational operator

C# equality or relational operator

Example of C# condition

Meaning of C# condition

Equality operators == x == y x is equal to y != x != y x is not equal to y Relational operators > > x > y x is greater than y < < x < y x is less than y >= x >= y x is greater than or equal to

y <= x <= y x is less than or equal to y Fig. 3.18 Equality and relational operators.

Comparison.cs

1 // Fig. 3.19: Comparison.cs

2 // Using if statements, relational operators and equality

3 // operators.

4

5 using System;

6

7 class Comparison

8 {

9 static void Main( string[] args )

10 {

11 int number1, // first number to compare

12 number2; // second number to compare

13

14 // read in first number from user

15 Console.Write( "Please enter first integer: " );

16 number1 = Int32.Parse( Console.ReadLine() );

17

18 // read in second number from user

19 Console.Write( "\nPlease enter second integer: " );

20 number2 = Int32.Parse( Console.ReadLine() );

21

22 if ( number1 == number2 )

23 Console.WriteLine( number1 + " == " + number2 );

24

25 if ( number1 != number2 )

26 Console.WriteLine( number1 + " != " + number2 );

27

28 if ( number1 < number2 )

29 Console.WriteLine( number1 + " < " + number2 );

30

31 if ( number1 > number2 )

32 Console.WriteLine( number1 + " > " + number2 );

33

Relational Operators

Relational Operators

Please enter first integer: 2000 Please enter second integer: 10002000 != 10002000 > 10002000 >= 1000

Please enter first integer: 1000 Please enter second integer: 20001000 != 20001000 < 20001000 <= 2000

Please enter first integer: 1000 Please enter second integer: 10001000 == 10001000 <= 10001000 >= 1000

34 if ( number1 <= number2 )

35 Console.WriteLine( number1 + " <= " + number2 );

36

37 if ( number1 >= number2 )

38 Console.WriteLine( number1 + " >= " + number2 );

39

40 } // end method Main

41

42 } // end class Comparison

Relational Operators

Operators Associativity Type () left to right parentheses * / % left to right multiplicative + - left to right additive < <= > >= left to right relational == != left to right equality = right to left assignment Fig. 3.20 Precedence and associativity of operators discussed in this

chapter.

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 %=

Assignment Operators

Assignment operator Sample expression Explanation Assigns Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;

+= c += 7 c = c + 7 10 to c

-= d -= 4 d = d - 4 1 to d

*= e *= 5 e = e * 5 20 to e

/= f /= 3 f = f / 3 2 to f

%= g %= 9 g = g % 9 3 to g

Fig. 5.12 Arithmetic assignment operators.

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--

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

Increment and Decrement Operators

Operator Called Sample expression Explanation

++ preincrement ++a Increment a by 1, then use the new value of a in the expression in which a resides.

++ postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1.

-- predecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides.

-- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1.

Fig. 5.13 The increment and decrement operators.

Ví dụ: i=3, j=15;

Increment.csint c;

c = 5;

Console.WriteLine( c );

Console.WriteLine( c++ );

Console.WriteLine( c );

Console.WriteLine();

c = 5;

Console.WriteLine( c );

Console.WriteLine( ++c );

Console.WriteLine( c );

556 566

Increment and Decrement Operators

Operators Associativity Type

() ++ --

left to right right to left

parentheses unary postfix

++ -- + - (type) right to left unary prefix

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != left to right equality

?: right to left conditional

= += -= *= /= %= right to left assignment

Fig. 5.15 Precedence and associativity of the operators discussed so far in this book.

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

Logical and Conditional Operators

expression1 expression2 expression1 && expression2

false false false false true false true false false true true true Fig. 5.16 Truth table for the && (logical AND) operator.

expression1 expression2 expression1 || expression2

false false false false true true true false true true true true Fig. 5.17 Truth table for the || (logical OR) operator.

Logical and Conditional Operators

expression1 expression2 expression1 ^ expression2

false false false false true true true false true true true false Fig. 5.18 Truth table for the logical exclusive OR (^) operator.

expression !expression false true True false Fig. 5.19 Truth table for operator! (logical NOT).

Structured Programming Summary

Operators Associativity Type

() ++ --

left to right right to left

parentheses unary postfix

++ -- + - ! (type)

right to left unary prefix

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != left to right equality

& left to right logical AND

^ left to right logical exclusive OR

| left to right logical inclusive OR

&& left to right conditional AND

|| left to right conditional OR

?: right to left conditional

= += -= *= /= %=

right to left assignment

Fig. 5.21 Precedence and associativity of the operators discussed so far.

LogicalOperators.cs1 // Fig. 5.20: LogicalOperators.cs

2 // Demonstrating the logical operators.

3 using System;

4

5 class LogicalOperators

6 {

7 // main entry point for application

8 static void Main( string[] args )

9 {

10 // testing the conditional AND operator (&&)

11 Console.WriteLine( "Conditional AND (&&)" +

12 "\nfalse && false: " + ( false && false ) +

13 "\nfalse && true: " + ( false && true ) +

14 "\ntrue && false: " + ( true && false ) +

15 "\ntrue && true: " + ( true && true ) );

16

17 // testing the conditional OR operator (||)

18 Console.WriteLine( "\n\nConditional OR (||)" +

19 "\nfalse || false: " + ( false || false ) +

20 "\nfalse || true: " + ( false || true ) +

21 "\ntrue || false: " + ( true || false ) +

22 "\ntrue || true: " + ( true || true ) );

23

24 // testing the logical AND operator (&)

25 Console.WriteLine( "\n\nLogical AND (&)" +

26 "\nfalse & false: " + ( false & false ) +

27 "\nfalse & true: " + ( false & true ) +

28 "\ntrue & false: " + ( true & false ) +

29 "\ntrue & true: " + ( true & true ) );

30

Only true if both inputs are true

Only false if both inputs are false

The result is only true if both are true

Outputs a truth table for the conditional AND operator (&&)

Outputs a truth table for the conditional OR operator (||)

Outputs a truth table for the logical AND operator (&)

LogicalOperators.cs

Program Output

31 // testing the logical OR operator (|)

32 Console.WriteLine( "\n\nLogical OR (|)" +

33 "\nfalse | false: " + ( false | false ) +

34 "\nfalse | true: " + ( false | true ) +

35 "\ntrue | false: " + ( true | false ) +

36 "\ntrue | true: " + ( true | true ) );

37

38 // testing the logical exclusive OR operator (^)

39 Console.WriteLine( "\n\nLogical exclusive OR (^)" +

40 "\nfalse ^ false: " + ( false ^ false ) +

41 "\nfalse ^ true: " + ( false ^ true ) +

42 "\ntrue ^ false: " + ( true ^ false ) +

43 "\ntrue ^ true: " + ( true ^ true ) );

44

45 // testing the logical NOT operator (!)

46 Console.WriteLine( "\n\nLogical NOT (!)" +

47 "\n!false: " + ( !false ) +

48 "\n!true: " + ( !true ) );

49 }

50 }Conditional AND (&&)false && false: Falsefalse && true: Falsetrue && false: Falsetrue && true: True

Conditional OR (||)false || false: Falsefalse || true: Truetrue || false: Truetrue || true: True

Returns the opposite as the input

Returns false when the two conditionals are the same

If one is true the result is true

Outputs a truth table for the logical OR operator (||)

Outputs a truth table for the logical exclusive OR operator (||)

Outputs a truth table for the logical NOT operator (!)

LogicalOperators.csProgram Output

Logical AND (&)false & false: Falsefalse & true: Falsetrue & false: Falsetrue & true: True  Logical OR (|)false | false: Falsefalse | true: Truetrue | false: Truetrue | true: True  Logical exclusive OR (^)false ^ false: Falsefalse ^ true: Truetrue ^ false: Truetrue ^ true: False  Logical NOT (!)!false: True!true: False

Logical and Conditional Operators

Control Structures

add grade to total

add 1 to counter

total = total + grade;

counter = counter + 1;

Fig. 5.1 Flowcharting C#’s sequence structure.

1. Cấu trúc tuần tự

if Selection Structure

The if structure

Các phát biểuBiểu thức điều kiện

true

false

Fig. 5.3 Flowcharting a single-selection if structure.

if/else selection structure

Conditions

do somethingdo something else

false true

Fig. 5.4 Flowcharting a double-selection if/else structure.

if/else selection structure1. using System;2. using System.Collections.Generic;3. using System.Text;

4. namespace IfElse5. {6. class Program7. {8. static void Main(string[] args)9. {10. int num = 6;11. string msg = "";12. if (num < 0)13. msg = "The number " + num + " is negative";14. else if ((num % 2 ==0))15. msg = "The number " + num + " is event";16. else17. msg = "The number " + num + " is odd";18. if (msg !="")19. Console.WriteLine (msg);20. }21. }22. }

Conditional Operator (?:)

Conditional Operator (?:)

boolean value ? if true : if falseboolean value ? if true : if false

Console.WriteLine( grade >= 60 ? "Passed" : "Failed" ); Console.WriteLine( grade >= 60 ? "Passed" : "Failed" );

switch Multiple-Selection Structure

switch Multiple-Selection Structure

break;

case: a case a action(s)true

false

.

.

.

break;

case b action(s) break;

false

false

case: z case z action(s) break;

default action(s)

true

true

case: b

switch Multiple-Selection Structure

switch(weekday){ case 1:

Console.WriteLine (“You have selected Monday”);break;

case 2:Console.WriteLine (“You have selected Tuesday”);break;

default:Console.WriteLine (“Sunday is the Default choice!”);break;

}

Ví dụ 1

Loops Các loại vòng lặp

The While Loop The Do Loop The For Loop The foreach Loop

true

false

do somethingconditions

Fig. 4.5 Flowcharting the while repetition structure.

LoopLoop

Tương tự như C: while, do while, for

71

Phải là giá trị bool: true, false

while <điều kiện>{

// phần thân while

}

while <điều kiện>{

// phần thân while

}

do {

// phần thân do while

} while <điều kiện>;

do {

// phần thân do while

} while <điều kiện>;

for( khởi tạo biến lặp; <điều kiện theo biến lặp>; thay đổi biến lặp){

// phần thân for

}

for( khởi tạo biến lặp; <điều kiện theo biến lặp>; thay đổi biến lặp){

// phần thân for

}

LoopLoop

72

index = 10;while (index != 0){ Console.WriteLine(index); index--;}

index = 10;while (index != 0){ Console.WriteLine(index); index--;}

index = 0;do{ Console.WriteLine("Happens at least once"); }while (index < 0);

index = 0;do{ Console.WriteLine("Happens at least once"); }while (index < 0);

for(index = 0; index < 100; index++){ Console.Write(index); Console.Write("\t");}

for(index = 0; index < 100; index++){ Console.Write(index); Console.Write("\t");}

Giá trị {true, false}

foreachforeach

73

foreach( typedata identifier in objectArray){

// thân foreach

}

foreach( typedata identifier in objectArray){

// thân foreach

}

==

Chỉ sử dụng biến i cho mỗi lần lặpChỉ sử dụng biến i cho mỗi lần lặp

Sử dụng chỉ số mảng như bình

thường

Sử dụng chỉ số mảng như bình

thường

Math Class Methods The Math class

Allows the user to perform common math calculations Using methods

ClassName.MethodName( argument1, arument2, … ) List of methods are in Fig. 6.2

Constants Math.PI = 3.1415926535… Math.E = 2.7182818285…

Math Class MethodsMethod Description Example

Abs( x ) absolute value of x Abs( 23.7 ) is 23.7

Ceiling( x ) rounds x to the smallest integer not less than x

Ceiling( 9.2 ) is 10.0 Ceiling( -9.8 ) is -9.0

Cos( x ) trigonometric cosine of x (x in radians)

Cos( 0.0 ) is 1.0

Exp( x ) exponential method ex Exp( 1.0 ) is approximately 2.7182818284590451

Floor( x ) rounds x to the largest integer not greater than x

Floor( 9.2 ) is 9.0 Floor( -9.8 ) is -10.0

Log( x ) natural logarithm of x (base e) Log( 2.7182818284590451 ) is approximately 1.0

Max( x, y ) larger value of x and y (also has versions for float, int and long values)

Max( 2.3, 12.7 ) is 12.7 Max( -2.3, -12.7 ) is -2.3

Min( x, y ) smaller value of x and y (also has versions for float, int and long values)

Min( 2.3, 12.7 ) is 2.3 Min( -2.3, -12.7 ) is -12.7

Fig. 6.2 Commonly used Math class methods.

Math Class MethodsMethod Description Example

Pow( x, y ) x raised to power y (xy) Pow( 2.0, 7.0 ) is 128.0 Pow( 9.0, .5 ) is 3.0

Sin( x ) trigonometric sine of x (x in radians)

Sin( 0.0 ) is 0.0

Sqrt( x ) square root of x Sqrt( 900.0 ) is 30.0 Sqrt( 9.0 ) is 3.0

Tan( x ) trigonometric tangent of x (x in radians)

Tan( 0.0 ) is 0.0

Fig. 6.2 Commonly used Math class methods.

Method Definitions Cú pháp

public void MethodName () {

// Contains the code of what the method does}

Ví dụ: static void sapXep(int a, int b)

{int tam; tam=a; a=b; b=tam;

}

Method Definitions Định nghĩa Method có tham số và trị trả về

public ReturnType methodName(Param1, Param2, … )

{

//Contains the code of what the method does

//Contains the return value

}

Ví dụ:

long Tong(int a, int b)

{ long lngS;

lngS= a+b;

return lngS ;

}

<Class Name>.<Phương thức>(tham số) nếu trong cùng class thì có thể bỏ class Name

Ví dụ:private void btnNhan_Click(object sender, EventArgs e) { int intA; double dblB; intA = Convert.ToInt32(txtSoA.Text); dblB= Convert.ToDouble(txtSoB.Text); lblKQ.Text = HamTich(intA, dblB).ToString(); } double HamTich(int A, Double dblB) { // lenh cua ham return (A * dblB);

}

Calling Method

User-defined method Maximum

public double Maximum( double x, double y, double z )

{

double maximumValue = x;

if ( y > maximumValue )

maximumValue = y;

if ( z > maximumValue )

maximumValue = z;

return maximumValue;

} // end method Maximum

User-defined method Maximumpublic void DetermineMaximum()

{

Console.WriteLine( "Enter three floating-point values,\n" + " pressing 'Enter' after each one: " );

double number1 = Convert.ToDouble( Console.ReadLine() ); double number2 = Convert.ToDouble( Console.ReadLine() ); double number3 = Convert.ToDouble( Console.ReadLine() );

double result = Maximum( number1, number2, number3 );

Console.WriteLine( "Maximum is: " + result );

} // end method DetermineMaximum

Passing Arguments

Passing by value Send a method a copy of the object When returned are always returned by value Set by value by default

Passing by reference Send a method the actual reference point

Causes the variable to be changed throughout the program When returned are always returned by reference The ref keyword specifies by reference The out keyword means a called method will initialize it

refref, out, param, out, param ref: tương tự như truyền tham chiếu trong

C/C++ Từ khoá ref phải được dùng lúc gọi hàm Các tham số truyền dạng ref phải được khởi

tạo giá trị trước

83

Khai báo ref trước kiểu dữ liệu

sử dụng ref cho tham số khi gọi hàm

Reference and value parameters

void SquareRef( ref int x )

{

x = x * x;

}

void Square( int x )

{

x = x * x;

}

Original value of x: 5

Value of x after SquareRef: 25

Value of x after Square: 5

refref, , outout, param, param

out: tương tự như ref Khác ref là ko cần khởi tạo giá trị trước khi

truyền

85

Khai báo cho tham số

Dùng trước tham số khi gọi hàm

refref, , outout, , paramparam

86

3 phần tử3 phần tử 6 phần tử6 phần tử Mảng arrayMảng array

Luôn khai báo ở cuối danh sách tham số

Luôn khai báo ở cuối danh sách tham số

Value TypesValue Types

using System;class DataTypeTest{ public static void Main()   {     int variableVal = 100;     funcTest(variableVal); Console.WriteLine(“This value of the variable is {0}",variableVal);    }   static void funcTest (int variableVal)   { int tempVar = 10;       variableVal = tempVar*20;    }}

Reference Types

using System;class DataTypeTest{ public int variableVal;}class DataTypeTestRef{ static void Main() { DataTypeTest dataTest = new DataTypeTest(); dataTest.variableVal = 100; funcDataTypeTest(dataTest); Console.WriteLine (dataTest.variableVal); }

Reference Types - Contd

static void funcDataTypeTest(DataTypeTest dataTest) { int tempVar = 10;      dataTest.variableVal = tempVar*20; }}

Value types vs. Reference types

Value Reference

Variable Holds Actual Value Reference

Allocated Inline (Stack) Heap

Default Value Zero Null

Parameter to functions Copy Value Copy Reference

Keyword thisKeyword this

91

public class list{ private int size;

...

public SetSize (int size) { this.size = size; }

public class list{ private int size;

...

public SetSize (int size) { this.size = size; }

JumpJump

break Thoát khỏi vòng lặp

continue Qua bước lặp kế

goto Nhảy đến nhãn Sử dụng goto case <expression>, trong switch

92

returnreturn

Thoát khỏi hàm void

Trả về 1 giá trị của hàm

93

void Func1(int x) {

if (x == 0)

return;

...

}

void Func1(int x) {

if (x == 0)

return;

...

}

int max(int a, int b) { if (a > b) return a; else return b;}

int max(int a, int b) { if (a > b) return a; else return b;}

Ví dụ Viết Qua Methodsprivate void btnTru_Click(object sender, EventArgs e) { //int intHieu; //intHieu = MamHieu(); //lblKQ.Text = intHieu.ToString(); lblKQ.Text = MamHieu().ToString(); } int MamHieu() { int intA, intB; intA = Convert.ToInt32(txtSoA.Text); intB = Convert.ToInt32(txtSoB.Text); return intA - intB;}

Ví dụ Viết Qua Methodsprivate void btnTinh_Click(object sender, EventArgs e) { int intA, intB=0; double dblC; intA = Convert.ToInt16( txtSoA.Text); intB = Convert.ToInt32( txtSoB.Text); lblATruoc.Text = intA.ToString(); lblBTruoc.Text = intB.ToString(); lblSoCTruoc.Text = dblC.ToString(); Tinh(intA, ref intB, out dblC);

lblASau.Text = intA.ToString(); lblBSau.Text = intB.ToString(); lblSoCSau.Text = dblC.ToString(); } void Tinh(int intA, ref int intB, out double dblC) { // out không phải gán giá trị trước khi thao tác intA += 10; intB += 10; dblC = 0; dblC += 10; dblC = Math.Sqrt(dblC); }

ArrayArray

Chứa một số những biến có cùng kiểu dữ liệu. Truy xuất phần tử thông qua chỉ số (index) Chỉ số bắt đầu bằng 0.

VD

int[] myInteger = new int[5]; string[] myString = {“BeMun”,”BeTien” };

96

Datatype[ ] array-nameDatatype[ ] array-nameDatatype[ ] array-nameDatatype[ ] array-name

Arrays

Fig. 7.1 A 12-element array.

-45

6

0

72

1543

-89

0

62

-3

1

6453

-78

Position number (index or subscript) of the element within array c

Name of array (Note that all elements of this array have the same name, c)

c[ 11 ]

c[ 10 ]

c[ 9 ]

c[ 8]

c[ 7 ]

c[ 4 ]

c[ 3 ]

c[ 2 ]

c[ 1 ]

c[ 0 ]

c[ 6 ]

c[ 5 ]

Creating an Array and Initializing Its Elements

Khai báo

<Datatype> [ ] <NameArray>;Ex:

int[ ] c; Tạo mảng và gán giá trị cho biến mảng

<NameArray> = new <Datatype> <[ARRAY_SIZE]>;Ex :

c = new int[ 12 ];

int [ ] c = new int[ 12 ];

ArrayArray

Lấy kích thước mảng qua thuộc tính Length int Size = myArray.Length;

Nếu thành phần của mảng là kiểu định trước, có thể dùng hàm Sort của Array để sắp xếp Array.Sort(myArray);

Dùng hàm Reverse của Array để đảo thứ tự các phần tử trong mảng Array.Reverse(myArray);

99

ArrayArray

100

Recommended