Wednesday, September 19, 2012

Beginner in C#: Understanding loops


What is a loop in programming?


A loop is as statement that helps you to execute a piece of code repeatedly, a known number of times or until a certain condition become true.
For example, if I said I'm going to walk exactly 500 steps, I'm making a loop about one step repeated 500 times. But if I said I'm going to walk until my dad calls me, here I don't know when exactly my dad will calls me, so this is a loop depending on a particular condition: "my dad is calling me", when it becomes true I will stop walking.

Loops in C#


The 3 most frequently used loops in C# are the following:

the "for" loop

The for loop is usually used to repeat a code N times, N could be a variable or a fixed integer (int).
here's how you write it:

int i; // Declaring an integer with the name 'i'
for(i=0;i<N;i++)
{
// YOUR CODE HERE
}

the "while" loop

The while loop is used to repeat an action until the condition (of type bool) becomes true. 
usage:
while(!condition)
{
// YOUR CODE HERE
}

the "do-while" loop

The do-while loop is just like the while, the only difference is that by its usage we ensure that your CODE is executed at least once.
usage:
do
{
// CODE
}while(!condition);
Its equivalent to:
// CODE
while(!condition)
{
// CODE
}