How to Use the for Loop Statement in C#
This tutorial describes how to use the C# for loop statement.
A for loop is a control flow statement that you allow you to execute a block of code repeatedly.
Related C# tutorials:
The for Loop Syntax
The syntax of the for loop statement is as follows:
for (initializer; condition; iterator) { //block of code }
Or if you need to create an infinite for loop, you can use the following syntax:
for ( ; ; ) { // Block of code. }
Examples
Example 1
You can use the for loop statement to loop through an array of numbers and print each number to the console, as the following code shows:
using System; namespace ForLoopExample { class Program { static void Main(string[] args) { int[] numbers = new int[] { 1, 10, 9, 8, 7, 4, 5, 3, 2, 6 }; for (int i = 0; i < numbers.Length; i++) { Console.WriteLine(numbers[i]); } } } }
Output:
1 10 9 8 7 4 5 3 2 6
Example 2
The following code is another example that shows you how to use the for loop statement:
using System; namespace ForLoopExample { class Program { static void Main(string[] args) { int[] numbers = new int[] { 1, 10, 9, 8, 7, 4, 5, 3, 2, 6 }; for (int i = numbers.Length - 1; i > 0; i--) { Console.WriteLine(numbers[i]); } } } }
Output:
6 2 3 5 4 7 8 9 10
Example 3
The following example shows you how to find the sum of numbers from 1 to 100:
using System; namespace ForLoopExample { class Program { static void Main(string[] args) { int total = 0; for (int i = 1; i <= 100; i++) { total += i; } Console.WriteLine("Total: " + total); } } }
Output:
Total: 5050
Example 4
The following example shows you how to create an infinite for loop:
using System; namespace ForLoopExample { class Program { static void Main(string[] args) { int count = 0; for (; ; ) { Console.WriteLine(count); if (count == 10) { break; } count++; } } } }
Output:
0 1 2 3 4 5 6 7 8 9 10
The loop breaks when the value of the variable count is equal to 10.
More C# tutorials:
In this tutorial, you have learned how to use the for loop statement. A for loop is a control flow statement that allows you to execute a block of code repeatedly.