In this tutorial you will learn how to use the for loop to repeat sections of code in the C# language. For loops are useful for when you want to repeat code a certain number of times. They are also very useful for efficiently working through all the elements in an array or going through each character in a string. For loops have a built in counter, condition, and increment. Watch the video below and then scroll down for the sample code.
Sample code
Example 1 – using for loop as simple simple counted loop
using System; namespace MyCSharpProject { class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { Console.WriteLine("Counter is: " + i); } Console.ReadLine(); } } }
Example 2 – using for loop to go through each character in string
using System; namespace MyCSharpProject { class Program { static void Main(string[] args) { string word = "dog"; for (int i = 0; i < word.Length; i++) { if (word[i] == 'a') { Console.WriteLine("This word contains the letter a"); } } Console.ReadLine(); } } }
Next tutorial: Do while loops in C#