Visual Basic 2010 (Console) Guide
For Loops

Iteration or repetition is the term used to refer to control statements that allow blocks of code to be repeated. The For loop allows the programmer to repeat code a specific number of times.

Example 1

Study the following code carefully. A for loop always has a stepper variable. This variable holds a different value on each iteration. The loop below counts from 1 to 10 inclusive.

Dim count As Integer
For count = 1 To 10
   Console.WriteLine("{0}.", count)
Next
Console.ReadLine()

For loops are sometimes referred to as For & Next loops. The statement Next (which can be followed by the stepper variable - eg Next count) marks the end of the block of code to be repeated.

Example 2

This example uses the Continue For statement to skip all of the even iterations.

Dim count As Integer
For count = 1 To 10
   If count Mod 2 = 0 Then Continue For
   Console.WriteLine("{0}.", count)
Next
Console.ReadLine()

Example 3

In this example, the loop counts in 10s. You can use a negative value for the Step part of the statement to get the loop to go backwards.

Dim count As Integer
For count = 10 To 100 Step 10
   Console.WriteLine("{0}.", count)
Next
Console.ReadLine()

Example 4

Dim count As Integer
Dim temp As Integer
Dim total As Integer = 0
For count = 1 To 10
   Console.Write("{0}. ", count)
   temp = Console.ReadLine()
   If temp = -1 Then Exit For
   total += temp
Next
Console.WriteLine("Total is {0}", total)
Console.ReadLine()

Having A Go

  1. Allow the user to input a message and a number. Display the message the specified number of times.
  2. Ask the user which times tables they would like to see. Use a loop to produce a lovely display of their chosen tables.
  3. Ask the user to enter 10 numbers. At the end, tell them the mean average, maximum and minimum of the values entered.
  4. A prime number is a number divisible only by itself and 1. Write a program that displays all of the prime numbers up to 10000.