Following types of iterative statements are there in C#.
- While
- Do While
- For
- Foreach
From the above the while, for, foreach are the statements under the category of entry controlled looping. and the statement do while statement falls under the exit controlled looping.
The major difference between entry and exit controlled looping is the position where the condition is evaluated. Also in entry controlled looping, initially the condition is false the iterative block will not be executed even once, but in exit controlled looping, even if the condition is false, the iterative block is executed once and then only the condition is evaluated.
While Statement
The statement block of while statement is executed while the boolean expression is true. It may execute zero or more times. If the boolean expression is false initially, the statement block is not executed.
The while statement is used to iterate while the condition evaluates to true.
Do While Statement
Do While is almost similar to While statement except it validate its boolean expression after the statement block. It guranttees that the statement block shall run atleast once for sure. Further iterations of the statement block continues while the boolean expression is true.
For Statement
The For statement iterate a code block until a specified condition is reached similar to while statement. The only difference of for statement has over while statement is that for statement has its own built-in syntax for intiliazing, testing, and incrementing/decrementing (3 clauses) the value of a counter.
The first clause is the initialize clause in which the loop iterators are declared.
The second clause is the boolean expression that must evaluate to a boolean type and the statement block is repeated until this expression is false.
The third clause is to increment/decrement the value that is executed after each iteration.
All three clauses must be separated by a semicolon (;) and are optional. For statement block is repeated zero or more times based on the boolean expression validation (second clause).
ForEach Statement
ForEach statement is desiged to loop through a similar type of items in a collection. As each element is enumerated, the identifier is assigned the new element, and the statement block is repeated. The scope of the identifier is within the foreach statement block. The identifier must be of the same type extracted from the collection and is read-only.
No comments:
Post a Comment