Learning C# Part 3: Control Structures

Written By: Kevin Jordan

- 02 Sep 2006 -

Description: This series aims to take a beginning programmer to an intermediate level in C#. Topics covered in Part 3 include: if/else statements, switch/case, and for, while, and do loops.

  1. If, Else Condition Statements
  2. Switch Statements
  3. for Loops
  4. do and while Loops
  5. Aww Man... Not Homework

for Loops

In C# you get a lot of way to repeatedly execute blocks of code over and over again. All of the loops execute while a boolean expression return true. I bet you can imagine the usefulness of these operations.

A for loop is a type of pretest loop because it evaluates the condition before any of the loop statements are executed. One thing to note in a for loop is that you should either know or be able to determine the number of iterations that your code block is going to need to perform. Let me show you an example and then I'll explain why.

for (int i = 0; i < 10; i++)
{
        Console.WriteLine("i = " +  i.ToString());
}

The code above first declares an integer, i, and initializes it to 0. Next it checks to see if the condition is met. Since 0 is less than 10 then the code block will be executed. After the code is done executing, the final part of our loop is performed (incrementing i by 1). You can perform any mathematical operation in place of i++, but you'll typically see it either increase or decrease by 1 at a time.

As you can see, the for loop is pretty much focused on i (some integer we just created for counting purposes), but we want to be able to test more than just the number of times the loop has been performed. Here's where the next two loops come in.

<< Previous

Next >>