Visual C# 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.

for (int count = 1; count <= 10; count++)
{
   Console.WriteLine("{0}.", count);
}
Console.ReadLine();

Example 2

If you want your program to miss out the loop on specific iterations, you can use the continue statement. It moves to the end of the current iteration and begins the next if there is one. This program only displays the odd numbers.

for (int count = 1; count <= 10; count++)
{
   if (count % 2 == 0)
   {
      continue;
   }
   Console.WriteLine("{0}.", count);
}
Console.ReadLine();

You can use the break; statement within a loop to force the loop to end prematurely if some condition or other is met.

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.