June 8, 2014
For Loop
Today, we will talk about loops. These loops help you to iterate through a collection object. For example, if you want to get the items present in an array, you can simply make use of loops. In C# language, there are 4 kind of loops.
- For.
- While.
- Do while.
- Foreach.
In this chapter, I will show you how to make use of for loop and in the later chapters, we will see how to make use of another loops. Using for loop, we can initialize a local variable, add a certain condition to be met, and add an increment to that variable. The for loop structure is given below.
for (int i = 0; i < condition ; i++) { }
A sample code is given below, where we are using a for loop to print out the items present in numbers array. We are simply iterating through the items and using the array index to print out the value.
using System; namespace MyHelloWorld { class Program { static void Main(string[] args) { int[] numbers = { 10, 20, 30, 40 }; for (int i = 0; i < numbers.Length; i++) { Console.WriteLine(numbers[i]); } } } }
Output:
10 20 30 40