C# can repeat a code block with a for loop. All for loops have a condition, this can be the amount of times or a list.

You need loops to repeat code: instead of repeating the instructions over and over, simply tell c# to do it n times.

For loops in C#

Example

The program below is an example of a for loop in c#. The for loop is used to repeat the code block. c# will jump out of the code block once the condition is true, but it won’t end the program.

The code block can contain anything, from statements to function calls.

1
2
3
4
5
6
7
8
9
10
11
12
13
using System;

namespace Loops {
class Program {
static void Main(string[] args) {

for (int i = 0; i < 4; i = i + 1) {
Console.WriteLine("iteration i: {0}", i);
}
Console.ReadLine();
}
}
}

The code block can be as many lines as you want, in this example its just one line of code that gets repeated.

csharp runs the code block only n times. The number of repetitions is called iterations and every round is called an iteration.

Exercises

  1. Can for loops exist inside for loops?
  2. Make a program that counts from 1 to 10.