Yorkville High School Computer Science Department
Yorkville High School Computer Science Department on Facebook  Yorkville High School Computer Science Department Twitter Feed  Yorkville High School Computer Science Department on Instagram

Yorkville High School Computer Science

ASSIGNMENTS: No Current Assignments

Computer Programming I :: Lessons :: 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<=14;i++)
MessageBox.Show("Final Fantasy " + i.ToString());

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

List Boxes

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

  1. Create a new button called "btnList"
  2. Change the Text Property to "Multiples of 10"
  3. Add a list box called "lstResults"
  4. Double-click the new button and add the following code:
lstResults.Items.Add("1");

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

  1. Add the following code to the TOP of the new button:
lstResults.Items.Clear();
  1. Use a for loop to get the first 10 multiples of 10 to appear in the list box
Yorkville High School Computer Science Department on Facebook Yorkville High School Computer Science Department Twitter Feed Yorkville High School Computer Science Department on Instagram