MorkaLork Development

Interesting stuff I've picked up over the years...

Loops

2009-04-16 17:58:51 | 196 views | loops for foreach while iterate iterating number

The basics



Loops are way to reduce code by running the same code over and over again. The most common loop is the for-loop that iterates from a start number to an end number. The iterating number can be used in the loop.

Example:


for (int i = 0;i <= 5 ;i++ ) {
Console.WriteLine(i);
}

This will output:
0
1
2
3
4
5

That's a basic loop.
There are 4 major ways to loop; For, Foreach, While, Do...While

For



As shown above the for loop iterates from a start number to an end number. This loop is great when you know how many times you want to loop. It's also good to use when you need an iterating number within the loop, using it as an indexer or such.

No example, look above.

Foreach



Foreach loops through every object in a collection. This loop is generally used with some sort of collection when you might now know the number of objects in the collection.



//Foreach with int
int[] numbers = new int[]{1, 2, 3, 4, 5};

Console.WriteLine("\nInt:");
foreach(int i in numbers)
{
Console.WriteLine(i);
}
/*Outputs:
* 1
* 2
* 3
* 4
* 5
*/


While



While is like a mix of for and foreach. You use it when you don't know the exact amount of times you want to loop. This is however more often used combined with objects than with index iterators, though it can be used just like a for loop as well:


int[] numbers = new int[]{1, 2, 3, 4, 5};
int count = 0;

//While with int
while (count < numbers.Length) {
Console.WriteLine(numbers[count]);
count++;
}
/*Outputs:
* 1
* 2
* 3
* 4
* 5
*/


Do...While



Do...while is just like the while loop but it checks the condition after looping at least once.



int[] numbers = new int[]{1, 2, 3, 4, 5};
int count = 0;
//Do...while with int
do
{
Console.WriteLine(numbers[count]);
count++;
} while (count < numbers.Length);
/*Outputs:
* 1
* 2
* 3
* 4
* 5
*/


The full code





//A collection
int[] numbers = new int[]{1, 2, 3, 4, 5};
//An iterator
int count = 0;

//While with int
while (count < numbers.Length) {
Console.WriteLine(numbers[count]);
count++;
}
/*Outputs:
* 1
* 2
* 3
* 4
* 5
*/
count = 0;

//Do...while with int
do
{
Console.WriteLine(numbers[count]);
count++;
} while (count < numbers.Length);
/*Outputs:
* 1
* 2
* 3
* 4
* 5
*/

//For loop with int
for (int i = 0;i <= 5 ;i++ ) {
Console.WriteLine(i);
}
/*Outputs:
* 1
* 2
* 3
* 4
* 5
*/

//Foreach with int
foreach(int i in numbers)
{
Console.WriteLine(i);
}
/*Outputs:
* 1
* 2
* 3
* 4
* 5
*/

Console.Read();



Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.