How to use a C# for loop

The for loop in C# is useful for iterating over arrays and for sequential processing. That is the statements within the code block of a for loop will execute a series of statements as long as a specific condition remains true. E.g.:

for(initialization; condition; increment) {
	statement/s
}

initialization :   Initialize the value of variable
condition :            Evaluate the condition based on the variable
increment :            Step taken for each execution of loop body

The for loop initializes the value before the first step. Then checks the condition against the current value of the variable and executes the statement/s inside the loop before incrementing.

int count = 4;
for(int i = 0; i < count; i++) {
	MessageBox.Show("The first number is: " + i);
}

This outputs:

The first number is: 0
The first number is: 1
The first number is: 2
The first number is: 3

The loop executes four times because we set the condition as being i is less than count, and i was initially 0.

All expressions in a for loop declaration are optional. The following creates an infinite loop:

for( ; ; ) {
	statement/s
}

in much the same way as simply using while(true) creates an infinite loop, e.g.:

while(true) {
	statement/s
}

Happy looping!

Advertisements

About Cameron
I'm a final year Computer Science/Information Systems major. Already finished my BA in Politics/Philosophy. I do web and software freelance on the side, while I finish studying. Hoping to be self-employed by the end of my degree, otherwise off into the real-world I go....

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: