Oct 20, 2010 08:27 PM
(This post was last modified: Oct 21, 2010 08:31 AM by Pulser.)
C# Loops
What Is It:
A loop basically "loops" through a block of code until a condition is met or a preset number is reached. A loop can be used to constantly check a value or do something over and over!
Getting started
In For Loops:
If you want something to execute 10 times you would use the number "10", however, the number will only "technically" reach 9. If you want a code to execute 9 times, you will use 10 - 1.
To begin a for loop, insert the following into a new button:
Code
for (int i = 0; i < 10; i++)
{
MessageBox.Show("This is a loop" + " " + "The Number of times executed is:" + " " + i);
}The first line begins the for loop. Inside of the brackets is the condition. It says as long as the integer "i" is less than 10 it will "i++" (says to add one each time you round the loop.)
The second line, inside of the curly brackets is the code that is being looped. So, in this case it is going to pop up a messagebox as well as the number of times the code has been looped through!
Spoiler (Click to View)
Do While Loop:
The Do While Loop simply executes a block of code while a condition is true.
Getting Started:
To begin a While Loop, create a progress bar, as well as a button. Insert the following:
Code
while (progressBar1.Value < 100)
{
progressBar1.Value += 1;
}The first line says that the code will execute as long as the progress bar is under 100 it will loop.
The second line will add 1 to the current value of the progressBar.
In order to check and see if the progressBar is at the maximum value we must use an If statement. (See other tut for more info)
Code
if (progressBar1.Value == progressBar1.Maximum)
{
MessageBox.Show("100");
}
else
{
// Do Nothing
}A while loop can be used to check a condition over and over!
Spoiler (Click to View)
Code:
For Loop:
Code
{
for (int i = 0; i < 10; i++)
{
MessageBox.Show("This is a loop" + " " + "The Number of times executed is:" + " " + i);
}
}While Loop:
Code
while (progressBar1.Value < 100)
{
progressBar1.Value += 1;
}
if (progressBar1.Value == progressBar1.Maximum)
{
MessageBox.Show("100");
}
else
{
}http://www.pulsecodes.info
Computer and Information Science major.
Information Technology Apprentice.
Freelance Programmer.
Computer and Information Science major.
Information Technology Apprentice.
Freelance Programmer.



