C# For Loop
A for loop is a loop that gathers its start, its condition, and its change in one header. The header sits in parentheses after the for keyword.
Counting to five
The counter starts at 1 and grows by 1. The loop stops after printing 5.
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
}
}Even numbers
The change part adds 2 on each pass. The counter prints the even numbers from 2 to 10.
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 2; i <= 10; i += 2)
{
Console.WriteLine(i);
}
}
}Chars by index
The index counts from 0 up to the string length. Each pass prints the char at that index.
using System;
class Program
{
static void Main(string[] args)
{
string word = "cat";
for (int i = 0; i < word.Length; i++)
{
Console.WriteLine(word[i]);
}
}
}Example
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 3; i++)
{
Console.WriteLine("7 x " + i + " = " + (7 * i));
}
}
}Key points
- The header holds three parts split by semicolons.
- The first part sets the starting value.
- The second part is the condition checked before each pass.
- The third part changes the counter after each pass.
- An index in square brackets reads one char of a string.
In this example, i starts at 1. The first pass prints "7 x 1 = 7". The second pass prints "7 x 2 = 14". The third pass prints "7 x 3 = 21". The condition then fails and the loop stops.
Note
A for loop fits well when the count of passes is known in advance.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
Exercise
Which part of a for header runs after each pass?