Iterative Statements in C# (Loops in C#)

SheoNarayan
Posted by in C# category on for Beginner level | Views : 11255 red flag

Iterative statements repeat a particular statement block until a condition has been satisfied.

Following types of iterative statements are there in C#.

  1. While
  2. Do While
  3. For
  4. Foreach
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.

int i = 9;

int j = 7;

int sum = 0;

while (j < i)

{

sum += j;

j++;

}

The value in the sum variable will be 15 as this loop will continue 2 times only. As soon as the value of j will reach to 9 the condition j < i will return false and the loop will break.

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.

int i = 9;

int j = 10;

int sum = 0;

do

{

sum += j;

j++;

} while (j < i);

The value in the sum variable will be 10 as j is already greater than i so after first time entering into the loop, the boolean validation (j < i)will return false and loop will break. The above code block may not be the good example of the do while loop; do while can be used to ask for the desired input from the user. If we are not getting the desired input, we can continue asking the question in the while statement block.

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

int j = 10;

int sum = 0;

for (int i = 0; i < j; i++)

{

sum += i;

}

The value of sum variable will be 45 (0+1+2+3+4+5+6+7+8+9). It will add all the number from 0 to 9 because once it will reach 10 (third clause increase the value of i after each iteration), the second clause (boolean expression) will not satisfy and loop will break.

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.

string[] days = { "sunday", "monday", "tuesday" };

string output = string.Empty;

foreach (string s in days)

{

output = string.Concat(output, s + " > ");

}

The identifier of the above foreach loop is string s (because days array contains string so identifier must be of the same type). The value of the output variable will be "sunday > monday > tuesday > ". In the days array, we have three strings and in the foreach loop we are concatenating all the items of the loop.

When to use For and While Statement

We should use For statement when there is some type of counter and iterations is known at the time of initialization of the loop and While statement when there is no counter and number of iterations is not known at the begining of the loop.


Use of break and continue

If we want to break the loop for some reason (may be after looping and validating the item, we got the desired result); we can use break (break;) statement to prematurely exist from the loop.

If we want to skip a particular iterations and continue next iteration; we can use continue (continue;) statement. Continue statement transfers the control to the end of the statement block where the next execution continues.

Hope this will be helpful for the beginners.

Happy coding !!!

Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Raja on: 12/18/2008
Awesome Sheo. Very good explanations of all looping statements.

Thanks and keep it up!!!

Login to post response

Comment using Facebook(Author doesn't get notification)