Lessons.Programming.04

Programming Lesson 4:
For Loops

For Loops

A for loop works the same as a while loop, but it ensures you do not forget to increment the variable. We will see how to do this in C#.

  • 1. Create a new button called "btnFor"
  • 2. Change the Text Property to "For Loop"
  • 3. Double-click the button and add the following code:

for (int i=1;i<=5;i++)
   MessageBox.Show(i.ToString());

The code above will do the exact same thing as the while loop code. The variable i is generally used in for loops but you can use any variable name you want. The variable i automatically increases by 1 every time the loop finishes. The i++ part is what increases i by 1, although you could use any math formula you wanted to increase the variable. Notice that we did not use curly brackets because there is only one line contained in the for loop. This practice is optional and you can still use the curly brackets if you want.

Look at the example code below and try to determine the output that will appear in the MessageBoxes. Click the button below each code block for the answer.

for (int i=1;i<=5;i++)
   MessageBox.Show((i * 2).ToString());

for (int i=3;i<=7;i++)
   MessageBox.Show((i - 2).ToString());

for (int i=1;i<=13;i++)
   MessageBox.Show("Final Fantasy " + i.ToString());

for (int i=1;i<=5;i++)
   MessageBox.Show(i.ToString() + "+ 2 = " + (i + 2).ToString());

ListBoxes

A ListBox is similar to a TextBox, but it can span multiple lines of text. Although you can do that with a TextBox using the Multiline property, a ListBox is different because separate lines are stored as separate items. Let's test out a ListBox in our project.

  • 4. Create a new button called "btnList"
  • 5. Change the Text Property to "Multiples of 10"
  • 6. Add a ListBox called "lstResults"
  • 7. Double-click the new button and add the following code:

lstResults.Items.Add("1");

The code above should add the number 1 to the ListBox each time you click the button. However, what if we want the ListBox to clear each time it is clicked?

    8. Add the following code to the TOP of the new button:

lstResults.Items.Clear();

  • 9. Use a for loop to get the first 10 multiples of 10 to appear in the ListBox