Siêu thị PDFTải ngay đi em, trời tối mất

Thư viện tri thức trực tuyến

Kho tài liệu với 50,000+ tài liệu học thuật

© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Praise for C# 2.0: Practical Guide for Programmers 2005 phần 6 pot
MIỄN PHÍ
Số trang
26
Kích thước
407.5 KB
Định dạng
PDF
Lượt xem
1651

Tài liệu đang bị lỗi

File tài liệu này hiện đang bị hỏng, chúng tôi đang cố gắng khắc phục.

Praise for C# 2.0: Practical Guide for Programmers 2005 phần 6 pot

Nội dung xem thử

Mô tả chi tiết

112 Chapter 6: Statements and Exceptions ■

6.3.3 Iteration Statements

Iteration statements, or loops, allow a single statement or block to be executed repeat￾edly. The loop condition is a boolean expression that determines when to terminate the

loop. C# provides four kinds of loops: while, do-while, for, and foreach statements.

while Statement

EBNF The syntax of the while loop is:

WhileStmt = "while" "(" BooleanExpr ")" EmbeddedStmt .

EmbeddedStmt is executed zero or more times until the BooleanExpr evaluates to false.

Example:

Console.Write("Countdown: ");

int sec = 9;

while ( sec >= 0 )

Console.Write("{0} ", sec--);

Console.WriteLine("... Go!");

Output:

Countdown: 9 8 7 6 5 4 3 2 1 0 ... Go!

do-while Statement

EBNF The syntax of the do-while loop is:

DoStmt = "do" EmbeddedStmt "while" "(" BooleanExpr ")" ";" .

EmbeddedStmt is executed one or more times until the BooleanExpr evaluates to

false.

Example (giving the same output):

Console.Write("Countdown: ");

int sec = 9;

do

Console.Write("{0} ", sec--);

while ( sec >= 0 );

Console.WriteLine("... Go!");

■ 6.3 Embedded Statements 113

for Statement

The syntax of the for loop is: EBNF

ForStmt = "for" "(" ForInitializer? ";" ForCondition? ";" ForIterator? ")"

EmbeddedStmt .

and is equivalent to the following statements:

ForInitializer

"while" "(" ForCondition ")" "{"

EmbeddedStmt

ForIterator

"}"

where: EBNF

ForInitializer = LocalVarDecl | StmtExprList .

ForCondition = BooleanExpr .

ForIterator = StmtExprList .

Example (giving the same output):

Console.Write("Countdown: ");

for (int sec = 9; sec >= 0; --sec)

Console.Write("{0} ", sec);

Console.WriteLine("... Go!");

An infinite for loop that prints dots:

for (;;)

Console.Write(".");

is equivalent to the following while statement:

while (true)

Console.Write(".");

foreach Statement

The syntax of the foreach loop is: EBNF

ForeachStmt = "foreach" "(" Type Identifier "in" Expr ")" EmbeddedStmt .

The foreach statement enumerates the elements of a given collection and executes the

embedded statement for each one. The Type and Identifier declare a read-only itera￾tion variable to be used locally within the scope of the embedded statement. During the

loop execution, this iteration variable represents a collection element. A compilation error

Tải ngay đi em, còn do dự, trời tối mất!