"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Tuesday, February 8, 2011

loops in .net ( While, do-while, for, foreach )

Hi,
 Practically speaking, a loop is the primary building block of a program. We use loop to repeat a set of actions for a certain interval. Now if you think of these intervals, it could be a traversal from one number (called as start index) to another number (called as end index). Very often or probably out of 10 such loop eight times you loop a collection such that you start from 0 and loop until you point to the end of the sequence.
In C# (and VB.NET) we use while, do-while, for and foreach loop to loop through a set of instructions.
 C# comes with three basic types of loops.
1. While Loop : This kind of loop runs while the condition is satisfied.
while (x >= 0)
{
}
2. do-while : This loop runs at least once while the condition is satisfied.
do
{

} while (x >= 10);
3. for : This loop has three sections, index declaration, condition and increment/decrement section. For each call to the instruction the index is incremented and checked with the condition.
for (int i = 0; i < 10; i++)
 {
 }
These are the most basic loops and I hope you already know them and came across with it in your life. .NET introduces another loop called Foreach loop which specially works on an IEnumerable. Each collection in .NET is somehow implements IEnumerable and hence can be used as a part of foreach loop. Hence every sequence (or whatever class) when implements an IEnumerable will have the provision to enumerate through values using foreach.
var enumerable = Enumerable.Range(1, 100);
 foreach (var e in enumerable)
 {

 }

This is only a basic idea of loop. using foreach will be a good option because it's working like a goto statement, it is fine with goto as soon as the compiler generates this for you, but it will be horrible if the language does consists a large number of unconditional jumps

 Stay tune...


Have a nice day... 'N happy Coding :)

No comments: