for loop in Visual C# is a control flow statement, allowing code to be repeatedly executed. It’s particularly useful when you know the exact number of iterations in advance.
The general syntax of a for loop in C# is:
for (initialization; condition; increment) {
// code to be executed
}
- Initialization: Usually used to define the counter variable, but it’s optional.
- Condition: The loop continues as long as this condition evaluates to true. Once it evaluates to false, the loop ends.
- Increment: Typically used to increment the counter variable, but it’s optional.
Here is an example of a for loop in C#:
for (int i = 0; i < 5; i++) { Console.WriteLine(i); }
In this example, the counter i
is initialized to 0. As long as i
is less than 5, the loop continues and the value of i
is printed to the console. The i++
statement increments i
by 1 after each loop iteration. So, the loop will print the numbers from 0 to 4.
Here is another example where a for loop is used to iterate over an array:
string[] names = { "John", "Jane", "Jim", "Jill" };
for (int i = 0; i < names.Length; i++) { Console.WriteLine(names[i]); }
In this example, the for loop iterates over the names
array, printing each name to the console. The loop continues as long as i
is less than the length of the names
array.