For Loop In C#

In programming world, if we need to execute some function or statement again and again we need a loop. There are many types of loops in programming like for loop, while loop, do while loop. We will start off from for loop in this post and cover other loops in the following posts.






By using a for loop, we can run one or more statements repeatedly till a specified condition is met. This loop is helpful when we need to run the statement for a certain number of times.

Basic Structure Of 'for' Loop


for loop consists of three components:

  1. Initialization
  2. Condition
  3. Iterator

Initialization: This is the point where we initialize loop control variable which will be accessible only inside the loop. The initialization part executes only once at the start of the for loop.

Condition: This is the main part of the loop where a specific condition is checked. If the condition returns true then the loop continues to execute otherwise the loop exits out.

Iterator: This part is executed after the statement inside the loop is executed. Usually we increment or decrement the value of loop control variable in the iterator section..

Shown below is the basic structure of for loop where-in the components are separated by semicolon ';'


for(initialization; condition; iterator)
{
    //Code which is to be executed again and again
}

Example Of for Loop


for(int i=0; i < 5, i++)
{
    Console.WriteLine(i);
}

//Output
//0
//1
//2
//3
//4


This is a basic example of for loop. Here i is the loop control variable whose value is incremented by 1 after each iteration. And every-time before Console.WriteLine(i); statement is executed, condition part of the loop is validated and as we can see, when the value of i reaches 5, the loop exits and hence the last printed value of i is 4.

The above loop can be tweaked a bit to print the output in reverse order i.e. 4,3,2,1,0. Lets have a look to learn for loop to print the number in reverse order.


for(int i=4; i >= 0, i--)
{
    Console.WriteLine(i);
}

//Output
//4
//3
//2
//1
//0

This code prints number in reverse order, but notice that now i is initialized with value 4 and iterator decrements the value of i by 1 and the condition is now also changed.

Try yourself and find out various usages. Let us know if you any query or concerns. Happy Reading (refer full series here - C# Tutorial Index)





Comments

Popular posts from this blog

Just Maths - Views, View Groups and Layouts