Looping in C#
By Xav
Introduction
Hi, Xav here (again). Here we're going to see how loops are used in C#. The syntax is actually very similar to languages such as JavaScript and PHP, so if you are familiar with either of those languages then it will be absolutely no effort to learn the nuts and bolts of C#'s looping constucts.
What is looping?
Looping is a special component of code. Basically, loops are used to re-execute lines of code multiple times. Instead of having to write out the same code multiple times, you can simply use a loop. Also, you may not know at the time how many times a piece of code needs to occur.
The For Loop
The For loop is used to execute the code a specific number of times. It has the following syntax:
for (initialisation; decision; increment)
{
//Code to loop goes here.
}
The main line is the "for" line. After the for keyword is used, the three settings are stated within brackets. For example:
for (int i = 1; i <= 100; i++)
{
MessageBox.Show("We are on message number " + i.ToString() + ".");
}
This would display a message box 100 times, each one containing the number it was on. Notice how the "i" variable is available as a parameter - you can use it to reference the current recurrence.
So what is actually happening here? Well, first a new integer variable called "i" is created. This is then set to the value 1. It then checks if i (1) is smaller than 100 - it is, so it executes the code (remember, i = 1 at the moment). After the end bracket is reached, the code execution goes back to the top statement, and it uses i++ to add one to the variable. "i" now contains the value of 2. Again, it checks the condition, and executes the code again, this time using i = 2, until i goes beyond 100. After this, code execution resumes after the curly closing brace }.
So there you have it! Loops can be complex to understand, but they make things unbelievably simple to repeat code blocks. Most programs will use some sort of loop, and can be very effective. Also, you can use a "do" or "while" loop - but that's for another tutorial, as this one's getting too long to type. :)
Test yourself: Write a prime number generator, where you type in the upper and lower values, and it uses two nested "for" loops to find all the prime numbers between them. Hint: use modulus arithmetic, with the % symbol.
Have fun!
Xav ;)
P.S. If this helped you then please +rep my post. Leave any comments below!
Edited by Xav, 22 May 2008 - 08:53 AM.


Sign In
Create Account


Back to top









